How to generically constrain a parameter to be a member of a tuple?

108 Views Asked by At

As of Typescript 4.0 with named tuples, I'm wondering if the following is possible:

declare const foo: <T extends string[], U extends memberOf T>(xs: T, x: U) => void

declare const ALL_OPTIONS: ['Alice', 'Bob']


foo(ALL_OPTIONS, 'Carl')  // Error
foo(ALL_OPTIONS, 'Alice') // No Error

Basically I'm trying to constrain U to an element of the tuple, something like memberOf might exist in the same way that you could use keyOf if T was an Object.

1

There are 1 best solutions below

2
On BEST ANSWER

You can use U extends T[number], like this:

declare const foo: <T extends string[], U extends T[number]>(xs: T, x: U) => void

declare const ALL_OPTIONS: ['Alice', 'Bob']


foo(ALL_OPTIONS, 'Carl')  // Error
foo(ALL_OPTIONS, 'Alice') // No Error

Playground link