In TypeScript, I want to ensure that the argument to myFunction
is one of the keys of MyInterface
. That is, I want the type checking on arg
specified below.
export interface MyInterface {
option1: boolean;
option2: boolean;
option3: boolean;
option4: boolean;
}
myFunction(arg: 'option1' | 'option2' | 'option3' | 'option4'): void {
console.log("arg:",option)
}
Is there a way to get this behavior without hardcoding 'option1' | 'option2' | ...
? Does TypeScript allow anything similar to in spirit to arg: in MyInterface.keys
?
0
Yes, you can use the keyof
type operator.
function myFunction(arg: keyof MyInterface): void {
console.log("arg:", arg);
}
Playground link to code