TypeScript 4.9's satisfies
operator is super handy, allowing narrowly typed values that still match a wide definitions.
type WideType = Record<string, number>;
const narrowValues = {
hello: number,
world: number,
} satisfies WideType;
Is there any way to define one type as satisfying another?
type WideType = Record<string, number>;
type NarrowType = {
hello: 4,
world: 5,
} satisfies WideType;
For types where you want very-specific values it's possible to go through a value to a type:
type WideType = Record<string, number>;
const narrowValues = {
hello: 4,
world: 5,
} satisfies WideType;
type NarrowType = typeof narrowValues;
But it gets a little clunky if you're trying to deal with anything more complex:
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;
Also it'd be great to be able to do this without creating any extra JS code.
Satisfies
type that acts this way, as shown here. Does that fully address your question? If not, what am I missing? – Bozcaada