Looking to do something special in TypeScript with a class called Foo
. I want to create a static array named bar
using const assertion, where the values are restricted to the keys of Foo. This array will serve as the type for the function func
while also acting as a runtime check.
Here's my current setup: (more details in TS Playground)
class Foo { a?: string; b?: string; c?: string }
const bar = ['a', 'b'] as const // this should throw an error if 'd' is added to the array
function func(arg: typeof bar[number]) { // TypeScript should recognize arg as a key of Foo
// ...
// utilizing bar at runtime
}
I've also attempted:
const bar: (keyof Foo)[] = ['a', 'b']
// but now arg is considered any key of Food, accepting all keys not just 'a' and 'b'
const bar: (keyof Foo)[] = ['a', 'b'] as const
// results in an Error: The type 'readonly ["a", "b"]' is 'readonly' and cannot be assigned to the mutable type '(keyof Foo)[]
Pick
provides an object version that doesn't suit this scenario.
Is there a solution for this?