Typescript交集类型的右侧丢失当映射数组的该类型

huangapple go评论54阅读模式
英文:

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;
  })[]
}

Playground

英文:

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;
  })[]
}

Playground

huangapple
  • 本文由 发表于 2023年4月20日 04:35:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76058625.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定