The new satisfies
operator in TypeScript 4.9 is incredibly useful for creating narrowly typed values that still align with broader definitions.
type WideType = Record<string, number>;
const narrowValues = {
hello: number,
world: number,
} satisfies WideType;
Is there a way to specify one type as fulfilling another?
type WideType = Record<string, number>;
type NarrowType = {
hello: 4,
world: 5,
} satisfies WideType;
If you need very specific values for a type, you can reference a value to create a type:
type WideType = Record<string, number>;
const narrowValues = {
hello: 4,
world: 5,
} satisfies WideType;
type NarrowType = typeof narrowValues;
However, things can get more complicated when dealing with complex structures:
type TemplateType = `${number}-${number}`;
type UnionType = "FOO" | "BAR";
type WideType = Record<string, string>;
const narrowValues = {
hello: "" as TemplateType,
world: "" as UnionType,
blah: "" as string
} satisfies WideType;
type NarrowType = typeof narrowValues;
It would be ideal to achieve this without the need for additional JavaScript code.