下面的代码输出[ 5142, 5143 ]
,但我使用any
作为类型。
let a = [{ _id: 5142 }, { _id: 5143 }];
a = a.map((e: any) => {
return e._id;
});
console.log(a);
查看这些类型,我认为正确的类型应该是
a = a.map((e: { _id: number }) => {
但失败了。
我使用VSCode。它能告诉我正确的类型吗?或者有一个聪明的console.log(typeof)
技巧吗?
1条答案
按热度按时间zaq34kh61#
从根本上说,把
map
的结果赋值给其他东西,而不是a
,因为如果你把它赋值回a
,那么a
就必须被定义为number[] | { _id: number; }[]
(因为它开始是{ _id: number; }[]
,然后你试图把它变成number[]
)。如果你把它赋给其他东西,那么你根本不需要指定任何类型,TypeScript会正确地推断它们:
Playground链接
重用
a
是 * 可能的 *,但不清楚为什么要这样做。Playground链接
TypeScript的流分析可以让它看到,当调用
map
时,a
是{ _id: number; }[]
,所以我们不需要类型保护。Playground链接