gpt4 book ai didi

javascript - typescript 类型限制行为

转载 作者:行者123 更新时间:2023-11-30 20:26:26 25 4
gpt4 key购买 nike

我对 Typescript 世界还比较陌生,我只是在开发一个测试应用程序来让自己习惯它。所以我遇到了类型限制“不起作用”的奇怪(?)问题。

我在类中定义了一个数组,例如成员字段:

listings: Array<ICryptListingItem> = [];

界面是:

export interface ICryptListingItem {
name: string;
something: number;
}

为什么编译器可以做:

  this.listings = listings.data.map((listing) => {
return {
name: listing.name
}
});

listings.data.map 返回的对象没有实现数组的类型接口(interface)?我没有得到什么?

提前致谢。

最佳答案

TypeScript 会自动处理这个问题;您的代码示例缺少一些信息。例如:

export interface ICryptListingItem {
name: string;
something: number;
}

class MyThing {
listings: Array<ICryptListingItem> = [];

doSomething() {
const listings = {
data: [
{ name: "the keeper" },
{ name: "the seeker" }
]
};

// Error here, as expected
this.listings = listings.data.map((listing) => {
return {
name: listing.name
}
});
}
}

可能 listingslistings.data 的类型是 any,所以 map 的结果call 也是anyany 总是允许分配给 this.listings 的类型。

关于javascript - typescript 类型限制行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50864777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com