首页 > 解决方案 > 如何在 Typescript 中添加多个断言

问题描述

我正在尝试下面的代码,但不确定是否可以告诉 typescript 假设来自任一接口的类型

export interface CellA {
    text: string;
}

export interface CellB {
    date: Date;
}

var cell = {};

const { date, text } = cell as (CellA | CellB);

console.log(date, text);

TS 错误:“CellA”类型上不存在属性“日期”| 单元格 B'.(2339)

我所追求的是让打字稿假设被破坏的变量存在于任何一个接口中。TS 游乐场示例

标签: javascripttypescriptassertion

解决方案


cell你这样做的方式是做出既具有又具有date它的假设text。但是,当您指定cell为 aCellACellB类型时,打字稿会抱怨,因为每种类型都缺少其中一个属性。

你可以只分配可选属性吗?像这样:

interface CellType {
  date?: Date,
  text?: string
}

const { date, text } = cell as CellType

或者,如果您真的想强制 acell严格地成为这些类型之一,我会在您定义变量时这样做:

interface CellA {
  text: string;
}

interface CellB {
  date: Date;
}

type CellType = CellA | CellB

const cell: CellType = { ... }

推荐阅读