【问题标题】:Determining type based on it's props根据它的道具确定类型
【发布时间】:2021-12-08 04:50:12
【问题描述】:

我有这两种类型:

export type Equipment = {
  id: string;
  name: string;
  path: WorkCenter[];
  key?: string;
  pathToElement?: string[];
  machine_id?: StatesData.MachineMapping['machine_id'];
  machine_codes?: StatesData.MachineMapping['machine_codes'];
  timeout_s?: StatesData.MachineMapping['timeout_s'];
  stateMachines?: StatesData.MachineState['machines'];
};

export type WorkCenter = {
  id: string;
  name: string;
  children?: Equipment[];
  key?: string;
  pathToElement?: string[];
  stateMachines?: StatesData.MachineState['machines'];
};

在我的代码中,有一个变量可以是EquipmentWorkCenter 类型。

我怎样才能确定它是什么?根据是Equipment 还是WorkCenter,我需要不同的逻辑来发生。

到目前为止,我接受了这个:

args: Equipment | WorkCenter

但想不出一个简单的方法来测试这是哪种类型。

执行typeof 最有意义,但它不适用于 ts 类型,因此不起作用。我也不能只测试仅存在于Equipment 上的属性,因为ts 将其视为不是联合。我错过了什么?

【问题讨论】:

  • 我想过这个。除非我错过了什么,否则最终会是这样:Property 'path' does not exist on type 'Equipment | WorkCenter'. Property 'path' does not exist on type 'WorkCenter'.ts。我是这样做的:if (args.path) {

标签: javascript typescript types


【解决方案1】:

我也不能只测试仅存在于 Equipment 上的属性,因为 ts 会将其视为非联合。

使用方括号表示法可以让您在没有 TS 抱怨的情况下进行测试

type TypeOne = {
  path: string;
};

type TypeTwo = {
  child: string;
};

const testIt = (t: TypeOne | TypeTwo) => {
  console.log(t['child']);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-03
    • 2011-04-27
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 2023-01-15
    • 2020-10-08
    • 1970-01-01
    相关资源
    最近更新 更多