Created
July 31, 2022 02:33
-
-
Save semlinker/9f757561fc4f28cf967592af81390a2f to your computer and use it in GitHub Desktop.
Use TypeScript Conditional Types Like a Pro
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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