【问题标题】:How to determine from 2 types either 1 or 2 [duplicate]如何从 2 种类型中确定 1 或 2 [重复]
【发布时间】:2019-08-23 12:17:12
【问题描述】:

我是打字稿的新手。

我有两种类型。

type Point = {
    x: number;
    y: number;
};

type Label = {
    name: string;
};

我有可变 Duko。

let Duko: ? = {...};

如何说Duko等于Label type或Point。

【问题讨论】:

标签: typescript


【解决方案1】:

使用union type

联合类型描述的值可以是多种类型之一。我们 使用竖线 (|) 分隔每种类型,因此 number | string | boolean 是值的类型,可以是 numberstringboolean.

因此:

let Duko: Point | Label = {...};

也是一个有趣的阅读:Typescript: Interfaces vs Types

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-08-25
  • 2021-05-04
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 2019-02-22
  • 2020-12-11
  • 1970-01-01
相关资源
最近更新 更多