2020-09-21

Prerequisite to understanding TypeScript Omit in React TypeScript Cheatsheet

selfnote, typescript, react

banner

Image by Edward Lich from Pixabay


title: Prerequisite to understanding TypeScript Omit in React TypeScript Cheatsheet date: "2020-09-21" published: true tags: "selfnote, typescript, react" author: Sung M. Kim banner: ./images/featured-image.jpg bannerCredit: "Image by Edward Lich from Pixabay"

Introduction

A note to self lest I forget the resources I learned from.

As I was going thru Swyx's React TypeScript Cheatsheet, Props: Omit prop from a type, I had trouble understand the definition of Omit.

1// this comes inbuilt with TS 3.52type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

Could not wrap my heads around it so Googled and found Marius Schulz's blog posts.

Blog read order

I read these backwards initially but the posts in following order seems to make sense.

  1. keyof and Lookup Types in TypeScript - Learn about keyof used for Omit and Exclude
  2. Conditional Types in TypeScript - To understand Exclude
    type Exclude<T, U> = T extends U ? never : T;
  3. The Omit Helper Type in TypeScript - To finally learn how Omit is implemented

References

Advaned utlity type document and sources for

  1. Omit<Type, Keys>

    • Definition: Constructs a type by picking all properties from Type and then removing Keys.
    • Documentation: https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys
    • Source: https://github.com/microsoft/TypeScript/blob/master/lib/lib.es5.d.ts#L1504
    1/**2 * Construct a type with the properties of T except for those in type K.3 */4type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
  2. Pick<Type, Keys>

    • Definition: Constructs a type by picking the set of properties Keys from Type.
    • Documentation: https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys
    • Source: https://github.com/microsoft/TypeScript/blob/master/lib/lib.es5.d.ts#L1480
    1/**2 * From T, pick a set of properties whose keys are in the union K3 */4type Pick<T, K extends keyof T> = {5  [P in K]: T[P];6};
  3. Exclude<Type, ExcludedUnion>

    • Definition: Constructs a type by excluding from Type all union members that are assignable to ExcludedUnion.
    • Documentation: https://www.typescriptlang.org/docs/handbook/utility-types.html#excludetype-excludedunion
    • Source: https://github.com/microsoft/TypeScript/blob/master/lib/lib.es5.d.ts#L1494
    1/**2 * Exclude from T those types that are assignable to U3 */4type Exclude<T, U> = T extends U ? never : T;

Misc. Link

Need to watch Marius Schulz's Egghead course, Advanced Static Types in TypeScript.


Image by Edward Lich from Pixabay

cuz, Donut's hole reminds me of Omit 😉