【发布时间】:2021-08-16 20:06:19
【问题描述】:
假设您有一个可以是数字或字符串数组的东西,并且您想要映射到这个数组。使用 TypeScript,以下表达这种情况的方式都被类型检查器接受。
[1, 2].map(e => console.log(e));
let arr: string[] | number[] = [1, 2];
arr.map(e => console.log(e));
但是如果我们添加一个显式的静态类型转换,到相同的类型,来描述 arr,编译器会按照我们的方式抛出一个错误:
(arr as string[] | number[]).map(e => console.log(e));
// Cannot invoke an expression whose type lacks a call signature.
// Type '(<U>(callbackfn: (value: string, index: number, array: string[]) => U, thisArg?: any) => U[]) | (...' has no compatible call signatures.
您知道为什么会发生这种情况吗,或者这可能是编译器本身的问题?
【问题讨论】:
-
要让它发挥作用,我相信你必须使用交集类型:
(arr as string[] & number[]).map(e => console.log(e));。要么,要么使用类型保护。