Skip to content

Instantly share code, notes, and snippets.

@cjdell
Created January 21, 2019 20:28
Show Gist options
  • Save cjdell/48bc519321b17dc18614b2410e23d5ad to your computer and use it in GitHub Desktop.
Save cjdell/48bc519321b17dc18614b2410e23d5ad to your computer and use it in GitHub Desktop.
Function accepts interface key of specific types
interface Colours {
red: string;
green: string;
blue: string[];
}
let colours: Colours;
export type PropertyNamesOfType<T, TT> = { [K in keyof T]: T[K] extends TT ? K : never }[keyof T] & string;
function getColourStr(colour: PropertyNamesOfType<Colours, string>): string {
return colours[colour] as string;
}
function getColourArr(colour: PropertyNamesOfType<Colours, string[]>): string[] {
return colours[colour] as string[];
}
// Success
getColourStr('red');
getColourArr('blue');
// Error
getColourStr('blue');
getColourArr('red');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment