Created
January 14, 2020 07:09
-
-
Save Roaders/df7f794b4fe8272ed16d15046530295d to your computer and use it in GitHub Desktop.
Typescript keyof for properties or functions
This file contains 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
interface IAddress{ | |
street: string | string[]; | |
town: string; | |
postcode: string; | |
} | |
interface IPerson { | |
id: number; | |
name: string; | |
isFemale: boolean; | |
dob: Date; | |
address: IAddress; | |
notes?: string; | |
nickName?: string; | |
call?: () => void; | |
rename: (name: string) => void; | |
calculateAge: () => number; | |
} | |
type FunctionKeys<T> = { [K in keyof T]: Required<T>[K] extends (...a: any[]) => any ? K : never }[keyof T] | |
type FunctionProperties<T> = Pick<T, FunctionKeys<T>>; | |
function handleFunction<T>(type: T, functionName: keyof FunctionProperties<T>) { | |
const value = type[functionName]; | |
} | |
type PropertyKeys<T> = { [K in keyof T]: Required<T>[K] extends (...a: any[]) => any ? never : K }[keyof T] | |
type PropertyProperties<T> = Pick<T, PropertyKeys<T>>; | |
function handleProperty<T>(type: T, functionName: keyof PropertyProperties<T>) { | |
const value = type[functionName]; | |
} | |
const person: IPerson = {} as any; | |
handleFunction(person, "calculateAge"); // accepts "call", "rename", "calculateAge" | |
handleProperty(person, "isFemale"); // accepts "address", "dob", "id", "isFemale", "dob", "address", "notes" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment