You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Think of types as sets of values (the type's domain). These sets can either be finite (e.g., boolean or literal types) or infinite (e.g., number or string).
TypeScript types form intersecting sets (a Venn diagram) rather than a strict hierarchy. Two types can overlap without either being a subtype of the other.
Remember that an object can still belong to a type even if it has additional properties that were not mentioned in the type declaration.
Type operations apply to a set's domain. The domain of A | B is the union of the domains of A and B.
Think of "extends," "assignable to," and "subtype of" as synonyms for "subset of."
Code Samples
constx: never=12;// ~ Type 'number' is not assignable to type 'never'.
// OK, {"A", "B"} is a subset of {"A", "B"}:constab: AB=Math.random()<0.5 ? 'A' : 'B';constab12: AB12=ab;// OK, {"A", "B"} is a subset of {"A", "B", 12}declarelettwelve: AB12;constback: AB=twelve;// ~~~~ Type 'AB12' is not assignable to type 'AB'// Type '12' is not assignable to type 'AB'
getKey({},'x');// OK, 'x' extends stringgetKey({},Math.random()<0.5 ? 'a' : 'b');// OK, 'a'|'b' extends stringgetKey({},document.title);// OK, string extends stringgetKey({},12);// ~~ Type 'number' is not assignable to parameter of type 'string'
constlist=[1,2];// ^? const list: number[]consttuple: [number,number]=list;// ~~~~~ Type 'number[]' is not assignable to type '[number, number]'// Target requires 2 element(s) but source may have fewer
consttriple: [number,number,number]=[1,2,3];constdouble: [number,number]=triple;// ~~~~~~ '[number, number, number]' is not assignable to '[number, number]'// Source has 3 element(s) but target allows only 2.
constbox: Lockbox={code: 4216};constrobox: ReadonlyLockbox={code: 3625};box.code=1234;// okrobox.code=1234;// ~~~~ Cannot assign to 'code' because it is a read-only property.