Created
January 21, 2019 20:28
-
-
Save cjdell/48bc519321b17dc18614b2410e23d5ad to your computer and use it in GitHub Desktop.
Function accepts interface key of specific types
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 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