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

housecor - 1581638360543600640

Previouserikras - 1457999235564154882Nexthousecor - 1586865516395876359

Last updated 2 years ago

Cory House () - October 16, 2022 at 9:29 PM

TypeScript tip:

Avoid making a property optional when the property isn’t valid in a certain case.

Instead, declare 2 separate types, and use Omit to avoid copy/paste.

Example: Many objects lack an id until they're saved. So declare a separate "Unsaved" type.

// Avoid making a property optional to support two separate scenarios. // Doing so redunces type safety. type User = { // Making id optional since unsaved users don't have an id yet. πŸ‘Ž id?: number; name: string; email: string; } // Instead, declare separate types. Then each scenario is fully type safe. πŸ‘ type User = { id: number; name: string; email: string; } // Separate type for unsaved users. // Deriving from the User type via Omit to keep types clean and lean. type UnsavedUser = Omit<User, "id">;

Tweet link
Thread by @housecor on Threadify Reader App
@housecor
#typescript
pic.twitter.com/Wzzx3DtYEE
housecor