如何在 typscript 中使用联合类型?[复制]

How to use union type in typscript? [duplicate]

提问人:Hyeonjae 提问时间:11/14/2023 更新时间:11/14/2023 访问量:36

问:

interface A {
  name : string;
  age : number;
}

interface B {
  name: string;
  address: string;
}

public samplefunction(data : A | B) : A | B{
  switch(data.name)
      case("John"):
          console.log(data.age), // ✖ Property 'age' does not exist on type...
      case("Kim"):
          console.log(data.address), //✖ Property 'address' does not exist on type
    ....
}

为什么console.log错误时会出现错误?

在此示例代码中,我想知道如何使用用户联合类型。

这种联合类型方法是否正确?

了解联合类型

打字稿 联合

评论

0赞 OGreeni 11/14/2023
用于合并接口和接口的属性,而不是并集。extendsAB
0赞 jcalz 11/14/2023
欢迎来到 Stack Overflow!在首先将属性从 缩小到 之前,不能假定它具有 。也许就像这种方法一样。不幸的是,这里的代码是伪代码或有错别字,只检查 for 和 for 的逻辑对我来说很难理解。无论如何,请查看链接问题的答案以获取更多信息。dataageA | BAage"John"address"Kim"
0赞 Hyeonjae 11/14/2023
谢谢大家。我解决了这个问题。

答: 暂无答案