typescript 如何找到Map元素的正确类型?

aamkag61  于 2022-11-18  发布在  TypeScript
关注(0)|答案(1)|浏览(123)

下面的代码输出[ 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)技巧吗?

zaq34kh6

zaq34kh61#

从根本上说,把map的结果赋值给其他东西,而不是a,因为如果你把它赋值回a,那么a就必须被定义为number[] | { _id: number; }[](因为它开始是{ _id: number; }[],然后你试图把它变成number[])。
如果你把它赋给其他东西,那么你根本不需要指定任何类型,TypeScript会正确地推断它们:

const a = [{ _id: 5142 }, { _id: 5143 }];

const b = a.map((e) => {
    return e._id;
});

console.log(b);

Playground链接
重用a是 * 可能的 *,但不清楚为什么要这样做。

let a: number[] | { _id: number; }[] = [{ _id: 5142 }, { _id: 5143 }];

a = a.map((e) => {
    return e._id;
});

console.log(a);

Playground链接
TypeScript的流分析可以让它看到,当调用map时,a{ _id: number; }[],所以我们不需要类型保护。

function example(a: number[] | { _id: number; }[]) {
    a = a.map((e) => {
        return typeof e === "object" ? e._id : e; // Note the type guard
    });

    return a;
}

console.log(example([{ _id: 5142 }, { _id: 5143 }]));

Playground链接

相关问题