typescript-tips

wesbos Wes Bos (@wesbos) - May 10, 2022 at 10:56 PM

🔥 Four ways to define an object type in TypeScript pic.twitter.com/km4PQ4nMWl

![// 1. We can manually define the keys with an interface or type interface Sizes { small: number; medium: number; large: number; } // 2. We can use the keys to define the types from a union type SizeList = ‘small’ ‘medium’ ‘large’; interface Sizes2 { [key in SizeList]: number; } // 3. A record does exactly as above, but puts it into a utility function type Sizes3 = Record<SizeList, number>; // 4. We can even make our own with Generics! let’s step through what all this means type MakeRecord<Keys extends string number symbol, ValType> = { [Prop in Keys]: ValType; } // 1. The key of an object can be a string, number, or symbol // 2. The value of an object can be any type, we pass it in as a generic ValType // 3. Loop over each key and set as a property on the type // 4. ValType will be whatever we pass in - in our case number type sizes4 = MakeRecord<SizeList, number>;](https://pbs.twimg.com/media/FSZ62g9XsAYbOSH.jpg)

Tweet link