typescript-tips

housecor Cory House (@housecor) - 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.

#typescript pic.twitter.com/Wzzx3DtYEE

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