Issue
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?
Solution
How about something like this?
class Foo { a?: string; b?: string; c?: string }
function getArgs<T extends ReadonlyArray<keyof Foo>>(args: T): T {
return args
}
const bar1 = getArgs(['a', 'b', 'c', 'd'] as const) // error
function func1(arg: typeof bar1[number]) {
// ...
const f = new Foo()
console.log('bar', bar1)
console.log('f[arg]', f[arg])
}
const bar2 = getArgs(['a', 'b'] as const)
function func2(arg: typeof bar2[number]) {
// ...
const f = new Foo()
console.log('bar', bar1)
console.log('f[arg]', f[arg])
}
func2('c') // error
Answered By - André Krosby
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.