'Const assertion with type requirements

In TypeScript, I have a class Foo and want to create a static array bar with const assertion where the values in the array are limited to the keys of Foo. The array is used as the type in func and also used as a runtime check.

Here's how I currently have it: (more details in TS Playground)

class Foo { a?: string; b?: string; c?: string }

const bar = ['a', 'b'] as const // need way for this to error if some 'd' which is not in Foo is added to the array

function func(arg: typeof bar[number]) { // TS should know arg is a keyof Foo as well
  // ...
  // some runtime usage of bar
}

I've also tried:

const bar: (keyof Foo)[] = ['a', 'b']
// but arg is now typed as any keyof Food, and accepts any key, not just 'a' and 'b'

const bar: (keyof Foo)[] = ['a', 'b'] as const
// throws an Error: The type 'readonly ["a", "b"]' is 'readonly' and cannot be assigned to the mutable type '(keyof Foo)[]

Pick gets an object version, so that doesn't work.

Is this possible?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source