Let's say I have a class:
class Test {
propA;
propB;
propC;
}
I want to create a method that returns an array of strings and type it to be only the keys existing in the Test class, how can I do this with the keyof
feature?
class Test {
propA;
propB;
propC;
getSomeKeys() : keyof Test[] {
return ['propA', 'propC']
}
}
You need to wrap the keyof Test
in brackets:
class Test {
//...
getSomeKeys() : (keyof Test)[] {
return ['propA', 'propC']
}
}
Note though, that keyof also includes getSomeKeys in this case.
Use Array<keyof Test>
:
class Test {
propA;
propB;
propC;
getSomeKeys(): Array<keyof Test> {
return ['propC'];
}
}
demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With