| { a: number; b: number; c: number; } | { a: number; b: number; c: number; d: number };
The last form is the most precise, but it may be less convenient to work with. If the problem with using an index signature is that string is too broad, then there are a few alternatives. One is using Record. This is a generic type that gives you more flexibility in the key type. In particular, you can pass in subsets of string: type Vec3D = Record<'x' | 'y' | 'z', number>; // Type Vec3D = { // x: number; // y: number; // z: number; // }
Another is using a mapped type. This gives you the possibility of using different types for different keys: type Vec3D = {[k in 'x' | 'y' | 'z']: number}; // Same as above type ABC = {[k in 'a' | 'b' | 'c']: k extends 'b' ? string : number}; // Type ABC = { // a: number; // b: string; // c: number; // }
Things to Remember • Use index signatures when the properties of an object cannot be known until runtime—for example, if you’re loading them from a CSV file. • Consider adding undefined to the value type of an index signature for safer access. • Prefer more precise types to index signatures when possible: interfaces, Records, or mapped types.
Item 16: Prefer Arrays, Tuples, and ArrayLike to number Index Signatures JavaScript is a famously quirky language. Some of the most notorious quirks involve implicit type coercions: > "0" == 0 true
Item 16: Prefer Arrays, Tuples, and ArrayLike to number Index Signatures
|
67