打字稿在地图功能的一种动态类型问题中具有多种类型

时间:2020-09-27 22:58:13

标签: typescript dictionary dynamic types interface

我想在相同的“动态”类型下使用相似但不同的类型,所以我做了:

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类型的任一类型但不能混合使用,如何使它与单个数组中的混合类型一起使用?

当前的解决方法是将data.map((candidate: any)=>{...}类型的任何内容都放进去,但我想通过正确的输入来做到这一点,而不仅仅是乱搞。

1 个答案:

答案 0 :(得分:0)

在您的exampleObject.ts中,您拥有:

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

问题在于打字稿默认会将type的类型扩展到string(而不是"plain" | "talented" | "experienced"),并且将无法检测到您的判别字段。您必须声明带有注释的单独变量:

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

或在各处添加as const,以告知打字稿不要扩大类型:

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