'How to set function's param as a key from interface
I have interface and object which represents this interface:
MyInterface {
variableOne: string;
variableTwo: boolean;
variableThree: boolean;
...
}
Also I have function toggleFunction(x) which gets a key and toggles it in my object. Which type do I need to set in param x in my toggle function to use it for toggle all boolean key in my object?
For example I need something like: toggleFunction(x: TYPE?)
Solution 1:[1]
Solution 2:[2]
You can use a conditional mapped type that I usually call KeysMatching:
type KeysMatching<T, V> = { [K in keyof T]: T[K] extends V ? K : never }[keyof T];
And then toggleFunction() can be defined like this:
declare const o: MyInterface; // or wherever it comes from
function toggleFunction(x: KeysMatching<MyInterface, boolean>) {
o[x] = !o[x];
}
toggleFunction("variableTwo"); // okay
toggleFunction("variableThree"); // okay
toggleFunction("variableOne"); // error!
Hope that helps; good luck!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kaya3 |
| Solution 2 | jcalz |
