When working with TypeScript, I am looking for a way to validate that the argument passed to myFunction
matches one of the keys defined in MyInterface
. Essentially, I want to enforce type checking on the arg
parameter as shown below.
export interface MyInterface {
option1: boolean;
option2: boolean;
option3: boolean;
option4: boolean;
}
myFunction(arg: 'option1' | 'option2' | 'option3' | 'option4'): void {
console.log("arg:", option)
}
I understand that I can use let myVar : keyof typeof obj
to specify a variable as one of the keys of an Object, as explained here. Is there a similar approach for Interfaces? Is it possible to achieve the desired behavior without explicitly listing 'option1' | 'option2' | ...
? In other words, is there a way to declare arg: in MyInterface.keys
?