Typescript Tips
  • Typescript Tips
  • docs
    • Contributor Covenant Code of Conduct
    • Contribution Guidelines
    • Deploy to Github Page Typescript Tips | typescript-tips
  • notes
    • Carlillo - 1591148366070747347
    • Steve8708 - 1605322303319199744
    • erikras - 1457999235564154882
    • housecor - 1581638360543600640
    • housecor - 1586865516395876359
    • housecor - 1596861970170671104
    • kulkarniankita9 - 1594154991148597250
    • mattpocockuk - 1506607945445949446
    • mattpocockuk - 1509850662795989005
    • mattpocockuk - 1509964736275927042
    • mattpocockuk - 1512388535692652547
    • mattpocockuk - 1536670032360611840
    • mattpocockuk - 1542079199543975937
    • mattpocockuk - 1590333383501979649
    • mattpocockuk - 1591047557702389760
    • mattpocockuk - 1592130978234900484
    • mattpocockuk - 1593584053042630657
    • mattpocockuk - 1598708710523772929
    • mattpocockuk - 1638562171863834625
    • mgechev - 1309379618034642946
    • mgechev - 1361186013029269506
    • mgechev - 1462654597059817481
    • sebastienlorber - 1512420374201446405
    • stackblitz - 1325818478675304448
    • stackblitz - 1328353096179789824
    • stackblitz - 1330890655351123968
    • sulco - 1160890708615716864
    • sulco - 1222507593287028736
    • wesbos - 1524040757518258176
    • wesbos - 1582803702225989637
    • wesbos - 1583093975359315968
    • wesbos - 1584905090628034560
    • wesbos - 1585258976421224450
    • wesbos - 1585641232155348992
    • wesbos - 1587082842110033926
    • wesbos - 1615777112408866832
Powered by GitBook
On this page
  1. notes

wesbos - 1524040757518258176

Previoussulco - 1222507593287028736Nextwesbos - 1582803702225989637

Last updated 2 years ago

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

🔥 Four ways to define an object type in TypeScript

// 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>;

Thread by @wesbos on Threadify Reader App
@wesbos
pic.twitter.com/km4PQ4nMWl
Tweet link
wesbos