为什么是这种数字类型?(TypeScript)


const arr = [1, 2, 3, 4] as const;
type Arr = typeof arr[number];
// expected & result type : 1 | 2 | 3 | 4
const doubledArr = arr.map(el => el * 2);
type DoubledArr = typeof doubledArr[number];
// expected type : 2 | 4 | 6 | 8
// result type : number

根据arr,我预期DoubledArr类型为2|4|6|8。但DoubleArr类型的数字出现了。如何将DoubledArr类型设置为2|4|6|8。

这种数学转换不是typescript可以静态计算出来的。如果你想将其作为结果类型,你需要断言它:

const doubledArr = arr.map((el) => el * 2 as 2 | 4 | 6 | 8 );
// OR:
const doubledArr = arr.map((el) => el * 2) as (2 | 4 | 6 | 8)[];

请记住,类型断言基本上是告诉typescript";我比你更了解,所以不要在这里检查我的工作;。如果您在断言中犯了错误,typescript将无法警告您(除非这是一个非常明显的错误(

如果这个功能请求实现了,它可能会包括这些功能,但我预计不会很快实现。

最新更新