首页 > 解决方案 > 打字稿需要密钥 A 或密钥 B

问题描述

我是打字稿的新手

我有一个接口 ABC,我希望 propA 或 propB 在那里。它还有其他属性

interface ABC {
  propA: string 
  propB: string 
  propC: string
  propD?: string 
}

我怎样才能做到这一点?

我是根据这个答案做的https://stackoverflow.com/a/40510700/10433835

interface ABC { 
   propC: string
   propD?: string 
}

interface A extends ABC {
  propA: string
}

interface B extends ABC {
    propB: string
}  

export type final = A | B

但是当我做这样的事情时

 function somethingCalled (a:A) {
 }

 const b:final = req.body 

 somethingCalled(b)

它引发以下错误 Argument of type 'final' is not assignable to parameter of type 'interface A'

标签: typescript

解决方案


我认为您想要的是使用区分联合,其中联合的单个对象由区分它们的属性来区分。在您的情况下,propA告诉它是A并且propB告诉它是B。以下是我们如何使用它们:

interface ABC {
  propC: string
  propD?: string 
}

interface A extends ABC {
  propA: string
  anotherA: number;
}

interface B extends ABC {
    propB: string
    somethingB: boolean;
}  

export type FinalType = A | B

 function somethingCalled (a:FinalType) {
     if('propA' in a){
         a.anotherA
         a.somethingB; // Error: Property 'somethingB' does not exist on type 'A'
     } else {
         a.somethingB
         a.anotherA // Error: Property 'anotherA' does not exist on type 'B'.
     }
 }

const req: any = '';

 const b:FinalType  =( req as any).body 

 somethingCalled(b)

一旦明确区分,您可以看到 Typescript 如何判断其他属性不属于该类型。

TS Playground 链接:https ://tsplay.dev/mpvDpw


推荐阅读