如何一般地将参数约束为元组的成员?

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

从带有命名元组的 Typescript 4.0 开始,我想知道以下是否可行:

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

基本上我试图将 U 限制到元组的一个元素,像 memberOf 这样的东西可能以与你可以使用 keyOf 相同的方式存在,如果 [=14] =] 是一个对象。

您可以使用 U extends T[number],像这样:

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