英文:
Righthand side of Typescript intersection type is lost when mapping over array of that type
问题
In the provided code, when using Array.map
on a collection of objects of MyType
, TypeScript loses the right-hand side of the intersection type ({value: string}
). However, when looping over the same collection with for ... of
, TypeScript correctly tracks the types. This behavior might be due to how TypeScript infers types within the context of Array.map
.
英文:
In the following code, when I try to use Array.map
on a collection of objects of MyType
, Typescript loses the right hand side of the intersection type ({value: string}
). However, when I loop over the same collection with for ... of
it tracks the types correctly. What's happening here?
(Typescript 5.0.2)
type MyType = {
containers: {
name: string;
}[] & {
value: string;
}[]
}
const data: MyType = {
containers: [{
name: "name",
value: "ddd",
}]
}
for (const container of data.containers) {
// This is fine
const { name, value } = container;
}
data.containers.map(container => {
// Property 'value' does not exist on type '{ name: string; }'.(2339)
const { name, value } = container;
})
答案1
得分: 2
The way myType
is defined it looks like an intersection of two arrays. Instead, you want a single array which can hold objects with both properties name
and value
.
Change myType to:
type MyType = {
containers: ({
name: string;
} & {
value: string;
})[]
}
英文:
The way myType
is defined it looks like an intersection of two arrays. Iinstead you want a single array which can hold object with both property name
and value
.
Change myType to
type MyType = {
containers: ({
name: string;
} & {
value: string;
})[]
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论