1

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.

jlouzado
  • 442
  • 3
  • 17
  • Possible duplicate of [Typescript derive union type from tuple/array values](https://stackoverflow.com/questions/45251664/typescript-derive-union-type-from-tuple-array-values) – ford04 Sep 24 '20 at 12:53
  • 1
    the potential duplicate does not answer the question directly, and the relevant information is buried deep in the answers. Importantly, I was unable to find it unless I specifically knew to search for `T[number]`; this question would help others find the answer to this specific problem. – jlouzado Sep 24 '20 at 13:10

1 Answers1

1

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

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875