Skip to main content

05 - satisfies: checking a catalog without losing its keys

Annotating an object literal with an interface costs you the list of its keys. The compiled proof, the real error and the rule for choosing.

What do you think about this article?

05 - satisfies: checking a catalog without losing its keys
TypeScript Avanzatofedericocalo.dev

At a Glance

Annotating an object literal with an interface costs you the list of its keys. The compiled proof, the real error and the rule for choosing.

The annotation that checks the type and throws the keys away

You have a hand-written catalog: an object literal with one entry per tool, or per route, or per language. You want two things at once. The first is for the compiler to check that every entry has the right shape, because there are dozens and a forgotten field is only a matter of time. The second is for a function elsewhere in the program to accept only the keys that really exist.

The way everyone tries to get them is to annotate the constant with an interface. It works for the first and destroys the second, and the reason it destroys it is not obvious: the annotation does not describe the value, it requalifies it. From that moment the compiler looks at the constant through the type you declared, and everything the type does not say is lost, even if it was written two lines above. This is the fifth article of the series and it rests on union types and on the exhaustiveness of article 04: you need to know what a literal type means and how the compiler reads it.

The errors reported are those of TypeScript 7.0.2, the latest version on the npm registry on 2026-11-13, tried with strict on. With 5.9.3 the codes and the positions are the same, but two details of form change that you will happen to see: version 7.0 orders the members of a string union alphabetically in the messages (5.9 gives them in declaration order), and writes the strings inside the type of an object in single quotes.

The proof that the information was lost

The type Record<string, VoceStrumento> says "an object with any text keys". It is not false, and it is much less than what you knew. The result does not have to be deduced: it can be checked. The trick, which I will use in the other blocks too, is to assign a value to the never type: the assignment always fails, and the error message prints the type the compiler actually computed.


interface VoceStrumento {
  titolo: string;
  categoria: 'rete' | 'testo' | 'immagini';
}

// Annotation: the type is checked, but the keys become 'string'.
export const strumentiAnnotati: Record<string, VoceStrumento> = {
  'json-formatter': { titolo: 'JSON formatter', categoria: 'testo' },
  'subnet-calculator': { titolo: 'Subnet calculator', categoria: 'rete' },
};

export type IdAnnotato = keyof typeof strumentiAnnotati;

// Compiles: with the annotation the key is 'string', so the typo passes.
export const refusoAccettato: IdAnnotato = 'json-formater';

// This compiles too: the declared type is VoceStrumento, the value is undefined.
export const vocePersa = strumentiAnnotati['chiave-inventata'];

console.log(refusoAccettato);
console.log(vocePersa);

// An impossible assignment is enough to make the compiler print the type of IdAnnotato.
export const sonda: never = null as unknown as IdAnnotato;

// Output of tsc 7.0.2:
// 01-annotato.ts(24,14): error TS2322: Type 'string' is not assignable to type 'never'.

// Output of node 24.11.0:
// json-formater
// undefined
      

In the block, IdAnnotato is keyof typeof strumentiAnnotati, and the last line shows that its type is string, not the list of the two keys: the list is not part of the declared type. That is why refusoAccettato compiles, although 'json-formater' does not exist: it is an identifier with a typo assigned to a variable that should accept only valid keys. vocePersa compiles too, and here the compiler gives the read the type VoceStrumento, not VoceStrumento | undefined. The Node output confirms it: at run time that read is undefined, and the first access to one of its fields throws. The only compiler error is the one from the final probes, put there on purpose.

The second part depends on an option worth knowing, because it is not inside strict. It is called noUncheckedIndexedAccess, and when it is on every read by index returns the type of the value joined with undefined, forcing you to handle the absence. In this project it is not set, so it has its default value, which is false: I checked by asking the compiler for the resolved configuration with npx tsc -p tsconfig.app.json --showConfig. It is the kind of flag worth turning on in a new project, and on a large one it produces hundreds of real errors, that is all the places where an index was read taking for granted that something was there. Here is what changes with the option on, on a test file:


interface VoceStrumento {
  titolo: string;
  categoria: 'rete' | 'testo' | 'immagini';
}

const strumentiAnnotati: Record<string, VoceStrumento> = {
  'json-formatter': { titolo: 'JSON formatter', categoria: 'testo' },
};

// With noUncheckedIndexedAccess the read by index includes undefined.
export const vocePersa = strumentiAnnotati['chiave-inventata'];
export const titolo = vocePersa.titolo;

// Output of tsc 7.0.2:
// 10-indice.ts(12,23): error TS18048: 'vocePersa' is possibly 'undefined'.
      

Line 12 no longer compiled: vocePersa is "possibly undefined", error TS18048, and to read the title you would first have to check that the entry exists. Without the option, the same file compiles (I tried it), and that is why the wide annotation is insidious: it takes away the keys and, by default, does not even warn you that a read can return nothing.

satisfies: checking without requalifying

The satisfies operator, added in TypeScript 4.9, does exactly what is needed: it checks that the value is compatible with a type and leaves the value with the type the compiler had deduced by itself.


interface VoceStrumento {
  titolo: string;
  categoria: 'rete' | 'testo' | 'immagini';
}

// satisfies: checks the type and keeps the literal keys.
export const strumenti = {
  'json-formatter': { titolo: 'JSON formatter', categoria: 'testo' },
  'subnet-calculator': { titolo: 'Subnet calculator', categoria: 'rete' },
} satisfies Record<string, VoceStrumento>;

export type IdStrumento = keyof typeof strumenti;

export function titoloDi(id: IdStrumento): string {
  return strumenti[id].titolo;
}

console.log(titoloDi('subnet-calculator'));

// Probes: an impossible assignment makes the compiler print the real type.
export const sondaId: never = null as unknown as IdStrumento;
export const sondaCategoria: never = strumenti['json-formatter'].categoria;

// Output of tsc 7.0.2:
// 02-satisfies.ts(21,14): error TS2322: Type '"json-formatter" | "subnet-calculator"' is not assignable to type 'never'.
//   Type '"json-formatter"' is not assignable to type 'never'.
// 02-satisfies.ts(22,14): error TS2322: Type '"testo"' is not assignable to type 'never'.

// Output of node 24.11.0:
// Subnet calculator
      

The difference from the previous block is one word and it changes three things. The probes at the bottom make them measurable: the first shows that IdStrumento is the union of the two identifiers, the second that categoria inside the constant has type 'testo', not the union of the three allowed categories.

  • The shape check stays: if an entry lacks categoria, or if its value is not among the three allowed, the block does not compile. It is the same service as the annotation.
  • The keys stay literal, so keyof typeof strumenti is the union of the two identifiers, and a function can accept that type instead of string.
  • The values stay narrow: categoria inside the constant has type 'testo', not 'rete' | 'testo' | 'immagini', so it can be used where that precise value is needed.

These are three guarantees of different natures. The first is a check at writing time and you get it with the annotation too; the other two are information that the compiler keeps after the check, and they are what makes the rest of the article possible. The doubt on which time is lost when you read keyof typeof for the first time is the order: typeof strumenti takes the type of the value, that is it moves from the world of values to that of types, and keyof extracts the union of its keys. Without typeof the compiler would look for a type called strumenti, which does not exist.

The error, when the identifier is wrong

This is the moment when all the work pays off. The message depends on where the typo is: the same wrong identifier produces two different errors depending on whether it is the argument of a function or the value assigned to a variable.


interface VoceStrumento {
  titolo: string;
  categoria: 'rete' | 'testo' | 'immagini';
}

const strumenti = {
  'json-formatter': { titolo: 'JSON formatter', categoria: 'testo' },
  'subnet-calculator': { titolo: 'Subnet calculator', categoria: 'rete' },
} satisfies Record<string, VoceStrumento>;

type IdStrumento = keyof typeof strumenti;

export function titoloDi(id: IdStrumento): string {
  return strumenti[id].titolo;
}

// Function argument: error with the allowed values, without a suggestion.
export const titolo = titoloDi('json-formater');

// Assignment to a variable: the same error, with the suggestion.
export const id: IdStrumento = 'json-formater';

// Output of tsc 7.0.2:
// 03-id-inesistente.ts(18,32): error TS2345: Argument of type '"json-formater"' is not assignable to parameter of type '"json-formatter" | "subnet-calculator"'.
// 03-id-inesistente.ts(21,14): error TS2820: Type '"json-formater"' is not assignable to type '"json-formatter" | "subnet-calculator"'. Did you mean '"json-formatter"'?
      

Both lines are rejected, and in both the compiler lists the allowed values. Only the assignment, error TS2820, adds the "Did you mean" suggestion, and in my experiment the suggestion does not appear on the function argument, which gives the TS2345 error. With the annotation that line would have produced no error, and the typo would have shown up as an empty page or an undefined value, at a point of the program that has nothing to do with the catalog.

The real gain: types that derive themselves

Keeping the literal keys is not only for avoiding a typo. It is because other types can be derived from that constant, and those types stay aligned with the catalog without anyone updating them. It is the part that changes the way a project is organized, and it shows better with the complete form.


interface VoceStrumento {
  titolo: string;
  categoria: 'rete' | 'testo' | 'immagini';
}

export const catalogo = {
  'json-formatter': { titolo: 'JSON formatter', categoria: 'testo' },
  'subnet-calculator': { titolo: 'Subnet calculator', categoria: 'rete' },
} as const satisfies Record<string, VoceStrumento>;

export type IdCatalogo = keyof typeof catalogo;

// The categories actually used, derived from the catalog and not rewritten by hand.
export type CategoriaUsata = (typeof catalogo)[IdCatalogo]['categoria'];

// A container that must have an entry for every tool: no omissions.
export type ConteggioPerStrumento = Record<IdCatalogo, number>;

export const conteggi: ConteggioPerStrumento = {
  'json-formatter': 0,
  'subnet-calculator': 0,
};

// Probe: the compiler tells which categories are present.
export const sonda: never = null as unknown as CategoriaUsata;

// Output of tsc 7.0.2:
// 04-catalogo.ts(25,14): error TS2322: Type '"rete" | "testo"' is not assignable to type 'never'.
//   Type '"rete"' is not assignable to type 'never'.
      

Three lines of this block deserve an explanation, because they are three distinct techniques that are reused in different contexts.

(typeof catalogo)[IdCatalogo]['categoria'] is an indexed access to a type, and it reads from left to right like an access to a value. It takes the type of the catalog, indexes it with the union of all the keys, and takes the categoria field of the result. Since the index is a union, the result is the union of the corresponding values: the probe shows "rete" | "testo", that is the categories actually used in the catalog. The difference from the union written by hand in VoceStrumento is substantial: that one lists the categories allowed, this one the categories present. If you remove the last network tool, this type narrows by itself.

Record<IdCatalogo, number> builds an object that must have one key for each tool, and none more. It is the technique that solves the most boring class of defects in a project with a catalog: the parallel table that lacks an entry. By forgetting one, and comparing it with the same omission on an object annotated with Record<string, number>, you see the difference:


interface VoceStrumento {
  titolo: string;
  categoria: 'rete' | 'testo' | 'immagini';
}

const catalogo = {
  'json-formatter': { titolo: 'JSON formatter', categoria: 'testo' },
  'subnet-calculator': { titolo: 'Subnet calculator', categoria: 'rete' },
} as const satisfies Record<string, VoceStrumento>;

type IdCatalogo = keyof typeof catalogo;

// 'subnet-calculator' is missing.
export const conteggi: Record<IdCatalogo, number> = {
  'json-formatter': 0,
};

// With the wide annotation the same omission passes in silence.
export const conteggiLarghi: Record<string, number> = {
  'json-formatter': 0,
};

// Output of tsc 7.0.2:
// 05-voce-dimenticata.ts(14,14): error TS2741: Property '"subnet-calculator"' is missing in type '{ 'json-formatter': number; }' but required in type 'Record<"json-formatter" | "subnet-calculator", number>'.
      

The first error names the missing key, "subnet-calculator". The second object, conteggiLarghi, produces no error: the absent entry would become an undefined value inside a count. That is why it pays to go around through the derived keys instead of writing the table against string.

What as const does, and what it does not do

In the catalog I wrote as const satisfies, and the first impression is that as const serves to keep the categories narrow. Measured, it is not so. The first file compares three variants of the same catalog, and the probe prints the categories that derive from them.


interface VoceStrumento {
  titolo: string;
  categoria: 'rete' | 'testo' | 'immagini';
}

// Only satisfies, without as const.
const solo = {
  'json-formatter': { titolo: 'JSON formatter', categoria: 'testo' },
  'subnet-calculator': { titolo: 'Subnet calculator', categoria: 'rete' },
} satisfies Record<string, VoceStrumento>;

type CategoriaSolo = (typeof solo)[keyof typeof solo]['categoria'];
export const sondaSolo: never = null as unknown as CategoriaSolo;

// Neither of the two: a wrong field enters the type.
const nessuno = {
  'json-formatter': { titolo: 'JSON formatter', categoria: 'testi' },
};
type CategoriaNessuno = (typeof nessuno)[keyof typeof nessuno]['categoria'];
export const sondaNessuno: never = null as unknown as CategoriaNessuno;

// Only as const: the wrong field enters the type and stays literal.
const soloConst = {
  'json-formatter': { titolo: 'JSON formatter', categoria: 'testi' },
} as const;
type CategoriaConst = (typeof soloConst)[keyof typeof soloConst]['categoria'];
export const sondaConst: never = null as unknown as CategoriaConst;

// Output of tsc 7.0.2:
// 06-senza-as-const.ts(13,14): error TS2322: Type '"rete" | "testo"' is not assignable to type 'never'.
//   Type '"rete"' is not assignable to type 'never'.
// 06-senza-as-const.ts(20,14): error TS2322: Type 'string' is not assignable to type 'never'.
// 06-senza-as-const.ts(27,14): error TS2322: Type '"testi"' is not assignable to type 'never'.
      

With satisfies alone, without as const, the category is still "rete" | "testo": the type the object must conform to contains literal strings, and the compiler keeps them. With neither, the category becomes string, and a typo such as 'testi' gets in without a warning. With as const alone the typo enters the type and stays literal, "testi": the type is narrow and wrong. That is why it is satisfies, not as const, that does the checking.

It remains to understand what as const adds. The following file shows it on two different fields.


interface VoceStrumento {
  titolo: string;
  categoria: 'rete' | 'testo' | 'immagini';
}

const solo = {
  'json-formatter': { titolo: 'JSON formatter', categoria: 'testo' },
} satisfies Record<string, VoceStrumento>;

const conConst = {
  'json-formatter': { titolo: 'JSON formatter', categoria: 'testo' },
} as const satisfies Record<string, VoceStrumento>;

// The title: without as const it is string, with as const it is the literal text.
export const s1: never = solo['json-formatter'].titolo;
export const s2: never = conConst['json-formatter'].titolo;

// Modifying an entry: without as const you can, with as const you cannot.
solo['json-formatter'].categoria = 'immagini';
conConst['json-formatter'].categoria = 'immagini';

// Output of tsc 7.0.2:
// 09-as-const.ts(15,14): error TS2322: Type 'string' is not assignable to type 'never'.
// 09-as-const.ts(16,14): error TS2322: Type '"JSON formatter"' is not assignable to type 'never'.
// 09-as-const.ts(19,1): error TS2322: Type '"immagini"' is not assignable to type '"testo"'.
// 09-as-const.ts(20,28): error TS2540: Cannot assign to 'categoria' because it is a read-only property.
      

It does two things. It makes literal the values that have no literal type to conform to: the titolo is string with satisfies alone and "JSON formatter" with as const. And it makes the object read-only: lines 19 and 20 are both rejected, but for different reasons. Line 19 because 'immagini' is not 'testo', the type that the category kept (TS2322); line 20 regardless of the value, because the property is read-only (TS2540). For a catalog that must not change at run time, read-only is the right choice.

When the annotation remains the right choice

satisfies does not replace the annotation in every case, and treating it as a replacement leads to using it where it is not needed. The difference lies in the direction in which you want the type to travel.

The annotation is for when the type is the contract and the value must conform: a configuration you pass to a library, an object that implements a public interface, a fallback value that must have exactly the shape expected elsewhere. There the requalification is the desired behavior, because you want whoever reads to see the contract and not the details of this instance. A doubt you hear repeated is that the error falls on a different point: I tried a catalog with a wrong category in one entry, annotated and with satisfies.


interface VoceStrumento {
  titolo: string;
  categoria: 'rete' | 'testo' | 'immagini';
}

// Annotation: the error falls on the wrong entry.
export const annotato: Record<string, VoceStrumento> = {
  'json-formatter': { titolo: 'JSON formatter', categoria: 'testo' },
  'subnet-calculator': { titolo: 'Subnet calculator', categoria: 'reti' },
};

// satisfies: where does the error fall?
export const controllato = {
  'json-formatter': { titolo: 'JSON formatter', categoria: 'testo' },
  'subnet-calculator': { titolo: 'Subnet calculator', categoria: 'reti' },
} satisfies Record<string, VoceStrumento>;

// Output of tsc 7.0.2:
// 08-posizione-errore.ts(9,55): error TS2322: Type '"reti"' is not assignable to type '"immagini" | "rete" | "testo"'.
// 08-posizione-errore.ts(15,55): error TS2322: Type '"reti"' is not assignable to type '"immagini" | "rete" | "testo"'.
      

In this experiment the two errors fall on the same line and the same column, 55, that is on the wrong value inside the entry. So the position of the message is not a reason to prefer the annotation: the reason is the contract. The only difference between the two lines of output is a matter of form, and concerns the order in which version 7.0 lists the members of the union, which I warned you about at the beginning.

satisfies is for when the value is the source of truth and the type is only a check: a catalog, a list of routes, a table of translations, anything from which you want to derive other types. The rule I use is this, and it is short: if from that constant you must derive a type with keyof or with an indexed access, you need satisfies; if the constant is a leaf that nobody queries, the annotation is perfectly fine and more readable.

There is a third case worth naming because it is the most frequent in real projects: a constant declared with as const and neither of the two things. as const freezes the literal types and checks nothing, as the 'testi' field of the previous file shows, which enters the type. The combination that gives everything is as const satisfies Tipo, where as const narrows and satisfies checks, and for a read-only catalog it is the form you would always use if it were not a bit wordy to read.

From a constant with its keys kept you can derive five different types, each useful at a different point of the program. They are independent of one another: you will use the ones you need.

  • keyof typeof c: the union of the identifiers, to be used as a function parameter instead of string.
  • (typeof c)[keyof typeof c]: the union of the entries, useful when a function accepts any entry of the catalog.
  • (typeof c)[K]['campo']: the type of a single field, to derive the categories present instead of those allowed.
  • Record<keyof typeof c, V>: a parallel table that cannot lack an entry.
  • Partial<Record<keyof typeof c, V>>: the same table when the entries are legitimately optional, which is the case of overrides.

The first two describe the set, the third goes down to a field, the last two build a structure parallel to the catalog. The fourth and the fifth are in tension on purpose: choosing between Record and Partial is deciding whether forgetting an entry is an error or is allowed, and that decision is better taken by the type than by the reviewer.


interface VoceStrumento {
  titolo: string;
  categoria: 'rete' | 'testo' | 'immagini';
}

const catalogo = {
  'json-formatter': { titolo: 'JSON formatter', categoria: 'testo' },
  'subnet-calculator': { titolo: 'Subnet calculator', categoria: 'rete' },
} as const satisfies Record<string, VoceStrumento>;

type Catalogo = typeof catalogo;

// 1. The identifiers.
export type Id = keyof Catalogo;
// 2. Any entry of the catalog.
export type Voce = Catalogo[Id];
// 3. The field of a specific entry, which depends on the identifier passed.
export function categoriaDi<K extends Id>(id: K): Catalogo[K]['categoria'] {
  return catalogo[id].categoria;
}
// 4. A table that cannot lack any tool.
export type Tutte = Record<Id, number>;
// 5. The same table when entries may be missing.
export type Alcune = Partial<Record<Id, number>>;

export const ridotte: Alcune = { 'subnet-calculator': 3 };

console.log(categoriaDi('subnet-calculator'), ridotte['json-formatter']);

// Probes: what the compiler derived.
export const s3: never = categoriaDi('subnet-calculator');
export const s2: never = null as unknown as Voce;
export const s5: never = null as unknown as Alcune;

// Output of tsc 7.0.2:
// 11-derivati.ts(31,14): error TS2322: Type '"rete"' is not assignable to type 'never'.
// 11-derivati.ts(32,14): error TS2322: Type 'Voce' is not assignable to type 'never'.
//   Type '{ readonly titolo: 'JSON formatter'; readonly categoria: 'testo'; }' is not assignable to type 'never'.
// 11-derivati.ts(33,14): error TS2322: Type 'Partial<Record<"json-formatter" | "subnet-calculator", number>>' is not assignable to type 'never'.

// Output of node 24.11.0:
// rete undefined
      

The block puts the five types in one file. The function categoriaDi uses the third: the type parameter K makes the result depend on the identifier passed, and the first probe shows that for 'subnet-calculator' the type is "rete", not the union of the categories. The other two probes show the entry as a read-only object and the optional table. Node prints rete and, for the entry that ridotte does not contain, undefined: it is the cost of Partial, which brings the absence back on stage.

What you can do now

You now know why annotating an object literal with an interface costs you the list of its keys, and you know how to check it instead of believing it: the identifier with the typo that compiles is the proof. You know that satisfies checks the shape without requalifying the value, and that this is what makes keyof typeof able to return a union of literal strings instead of string. You also know that it is satisfies and not as const that keeps the categories narrow, while as const in turn makes the other values literal and the catalog read-only.

You know the rule for choosing, which does not depend on taste: if you must derive a type from the constant, you need satisfies; if the constant must respect someone else's contract, you need the annotation. And you know that noUncheckedIndexedAccess exists, the flag outside strict that decides whether a read by index can return undefined: in this project it is off, verified with the resolved configuration.

In the next article, 06 on template literal types, the keys stop being a hand-written list and become a rule that the compiler knows how to compose, using the convention by which this project names the values it writes in the browser's storage. The work on data arriving from outside, which precedes all of this, is in article 02 and in article 03.

Frequently asked questions

What is the difference between annotating an object and using satisfies?

The annotation requalifies the value: from that moment the compiler looks at it through the declared type, and the extra information it had deduced from the literal is lost. satisfies checks compatibility and leaves the value with the deduced type, so the keys and the values stay literal.

Why does keyof on my object return string instead of the keys?

Because the object is annotated with an index type, for example Record<string, T>. In that type the list of keys does not exist, so keyof cannot return it. You need satisfies in place of the annotation.

What is typeof for inside keyof typeof?

To move from the world of values to that of types. strumenti is a constant, not a type: typeof strumenti takes its type, and keyof extracts the union of its keys. Without typeof the compiler would look for a type with that name and would not find it.

Can a read by index return undefined?

It depends on noUncheckedIndexedAccess, which is not part of strict. When it is on, every read by index returns the type joined with undefined, and the compiler flags the unchecked access with the TS18048 error. Without the option, a nonexistent key has a type that lies.

Is it worth combining as const and satisfies?

For a read-only catalog, yes: satisfies checks the shape and keeps the literal categories, as const makes the other values literal and the object read-only. On its own, as const checks nothing and a wrong field would enter the type.

The same series also includes Strict mode is not enough.

Sources

  • TypeScript 4.9 - the satisfies operator: the version in which satisfies was added, the definition and the example of the intercepted typo, page downloaded; consulted on 2026-11-13.
  • TypeScript Handbook - keyof: the behavior of keyof on types with an index signature, page downloaded; consulted on 2026-11-13.
  • TypeScript - noUncheckedIndexedAccess: the definition of the option and the example in which undefined is added to undeclared fields, page downloaded; consulted on 2026-11-13.
  • All the errors and outputs are produced by tsc --noEmit --strict --noImplicitReturns --target ES2022 --module ESNext --moduleResolution bundler file.ts (typescript 7.0.2, npm view typescript version on 2026-11-13) and by node file.ts (Node 24.11); for the file with noUncheckedIndexedAccess the option is added to the command line.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects