简体   繁体   English

如何在 TypeScript 中使用区分不同的 object 类型?

[英]How to use distinguish differenct object type in TypeScript?

How to distinguish different object type in TypeScript?如何区分TypeScript中不同的object类型?



interface CC {
    a: number;
    b: string
}

interface B {
    c:number
}



const obj:  CC |  B = {
    a: 1,
    c: 1
} 
// valid

I want the obj only valid when我希望 obj 仅在以下情况下有效

{
  a:number,
  b:string
}

or或者

{
  c:number
}

not what union type or intersection type behave.不是联合类型或交集类型的行为。

One way to force typescript to pick either B or CC is to set a common variable with a specific value.强制 typescript 选择BCC的一种方法是设置具有特定值的公共变量。

Example : 示例

type CC = {
    type: 1;
    a: number;
    b: string
};

type B = {
    type: 2;
    c: number
};

const obj: CC | B = {
    type: 1,
    a: 1,
    c: 1
};

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM