satisfies, as and annotations — three ways to state a type¶
Level: 201 · for TypeScript users choosing how to state a type
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: An annotation checks an object and forgets its details, satisfies checks it and keeps them, and as barely checks: { red: [255, 0, 0] } as Palette compiles without the required green, which satisfies Palette reports as TS2741.
Keywords: satisfies, as
What the finished page will answer¶
- What type does
greenhave in an object declared: Paletteand in one declaredsatisfies Palette, and which of them allowsgreen.toUpperCase()? - Why does
{ red: [255, 0, 0] } as Palettecompile withoutgreen, and what does readinggreengive at run time? - When does
asrefuse, as TS2352 does for42 as string, and what doesas unknown asdo about it? - Do
satisfiesand an annotation both report an extra property such asblue(TS2353)? - What does
as const satisfies Paletteadd oversatisfies Palettealone?
Examples it will need¶
-
satisfies_as_annotation_tserror.ts— TS2339 on the annotated object'sgreen, nothing on thesatisfiesone, nothing on theasone that lacksgreen, and TS2741 whensatisfiesmeets the same missing property -
satisfies_as_missing_property_ts.ts— theundefinedthat anas-asserted object holds wheregreenshould be
See also¶
- Annotations and inference — when to write a type at all
- Type assertions — how far an
ascan lie - Primitive and literal types — the literal types
satisfieskeeps and an annotation widens - Excess property checks — the extra-property check both forms apply
- Rust: Casting with
as↗ — anasin Rust converts the value; TypeScript's converts nothing