Skip to content

Instantly share code, notes, and snippets.

@semlinker
Created July 31, 2022 02:33
Show Gist options
  • Save semlinker/9f757561fc4f28cf967592af81390a2f to your computer and use it in GitHub Desktop.
Save semlinker/9f757561fc4f28cf967592af81390a2f to your computer and use it in GitHub Desktop.
Use TypeScript Conditional Types Like a Pro
type FunctionPropertyNames<T> = {
  [K in keyof T]: T[K] extends Function ? K : never;
}[keyof T];
type FunctionProperties<T> = Pick<T, FunctionPropertyNames<T>>;
type NonFunctionPropertyNames<T> = {
  [K in keyof T]: T[K] extends Function ? never : K;
}[keyof T];
type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>;
interface User {
   id: number;
   name: string;
   age: number;
   updateName(newName: string): void;
}
type T5 = FunctionPropertyNames<User>; // "updateName"
type T6 = FunctionProperties<User>; // { updateName: (newName: string) => void; }
type T7 = NonFunctionPropertyNames<User>; // "id" | "name" | "age"
type T8 = NonFunctionProperties<User>; // { id: number; name: string; age: number; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment