Skip to content

Instantly share code, notes, and snippets.

@Roaders
Created January 14, 2020 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Roaders/df7f794b4fe8272ed16d15046530295d to your computer and use it in GitHub Desktop.
Save Roaders/df7f794b4fe8272ed16d15046530295d to your computer and use it in GitHub Desktop.
Typescript keyof for properties or functions
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