映射函数在一个动态类型问题中打字稿多种类型

Typescript multiple types in one dynamic type issue with map function

我想在相同的 'dynamic' 类型下使用相似但不同的类型,所以我做了:

export type ICandidate = 
  | ICandidatePlain
  | ICandidateTalented
  | ICandidateExperienced

其背后的原因是因为候选人数组中的对象可以具有彼此不同的属性

ICandidate 类型工作正常,因为候选人只是对象的一部分:

export interface Process {
  id: string,
  name: string,
  candidates: ICandidate[]
}

后来发现了这个问题,因为我需要将所有候选人映射到他们的特定组件(取决于类型)。

here is a link to codesandbox, error on line #14

还有其他方法可以完成这项工作吗?

我猜测 map 需要具有完全相同属性的对象数组 - 或者来自类型 ICandidate 的任一类型但不是混合类型,我怎样才能让它在单个数组中使用混合类型?

当前的解决方法是将 any for type data.map((candidate: any)=>{...},但我想通过正确的输入来使其正确,而不仅仅是乱搞。

在你的 exampleObject.ts 你有:

//...
data: [
    {
      type: "plain",
      //...
    },
    {
      type: "talented",
      //...
    },
    {
      type: "experienced"
      //...
    }
  ]
...

问题在于 typescript 默认会将 type 的类型扩大到 string(而不是 "plain" | "talented" | "experienced"),并且它无法检测到您的鉴别器字段。您必须使用注释声明单独的变量:

const data : ICandidate[] = [...];

或在各处添加as const以告诉打字稿不要加宽类型:

data: [
    {
      type: "plain" as const,
      //...
    },
    {
      type: "talented" as const,
      //...
    },
    {
      type: "experienced" as const,
      //...
    }
  ]