简体   繁体   English

在 TypeScript 中键入具有联合类型的数组

[英]Type an Array with a Union type in TypeScript

I'd like to use this array with a union type, but TS rightly assumes that its type is string: "Argument of type 'string' is not assignable to parameter of type '"a" | "b"'."我想将此数组与联合类型一起使用,但 TS 正确地假定它的类型是字符串:“'string' 类型的参数不可分配给 '"a" | "b"' 类型的参数。”

function doSomething(value: "a" | "b"){}

["a", "b"].map(e => doSomething(e));

Is there a ways in which I can define the types of the array elements?有什么方法可以定义数组元素的类型吗? If not, is there another way to solve this problem?如果没有,是否有另一种方法可以解决这个问题? I do not want to cast it in map().我不想将它投射到 map() 中。

If you define the union type and add a type assertion, you can limit the type of that array to only accept union members.如果定义联合类型并添加类型断言,则可以将该数组的类型限制为仅接受联合成员。

type AorB = 'a' | 'b';
const testArray: AorB[] = ['a', 'b'];

function doSomething(value: AorB) {...};


const test2: AorB[] = ['b', 'c'] // <- Errors because 'c' is not part of the union.

The type needs to be narrowed at some point from string to AorB : either when defining the array to only accept AorB , using a type guard to narrow properly from string to AorB , or the in the receiving function.类型需要在某个时候从string缩小到AorB :在定义数组仅接受AorB时,使用类型保护将字符串从string正确缩小到AorB ,或者在接收 function 中。

The correct answer is using a const assertion :正确答案是使用const 断言

function doSomething(value: "a" | "b"){}

(["a", "b"] as const).map(e => doSomething(e));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM