Skip to content

Instantly share code, notes, and snippets.

@RomarQ
Last active March 17, 2022 16:02
Show Gist options
  • Save RomarQ/49ede8e1bd84ef67ab71c34e3206bef5 to your computer and use it in GitHub Desktop.
Save RomarQ/49ede8e1bd84ef67ab71c34e3206bef5 to your computer and use it in GitHub Desktop.
Typescript Cheat Sheet

Typescript Cheat Sheet

Make all properties in T optional

/**
 * Make all properties in `T` optional
 
 * @typeParam T - Object
 */
type Partial<T> = { [P in keyof T]?: T[P] | undefined; }

interface A {
 prop: string;
}

type B = Partial<A>;
// Result:
//  {
//    prop?: string;
//  }

Make U properties in T optional

/**
 * Make `U` properties in `T` optional
 *
 * @typeParam T - Object
 * @typeParam U - Object keys
 */
export type SelectivePartial<T, U extends keyof T> = Omit<T, U> & Partial<Omit<T, Exclude<keyof T, U>>>;

interface A {
 prop1: string;
 prop2: boolean;
}

type B = SelectivePartial<A, "prop2">;
// Result:
//  {
//    prop1: string;
//    prop2?: boolean;
//  }

Extract Props from a react component React.FC<Props>

/**
 * Extract `Props` from a react component `React.FC<Props>`
 *
 * @typeParam T - A React Component
 */
type ExtractProps<C> = C extends React.FC<infer Props> ? Props : never;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment