javascript - 如何在 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 游乐场示例
解决方案
cell
你这样做的方式是做出既具有又具有date
它的假设text
。但是,当您指定cell
为 aCellA
或CellB
类型时,打字稿会抱怨,因为每种类型都缺少其中一个属性。
你可以只分配可选属性吗?像这样:
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 = { ... }
推荐阅读
- php - 在php laravel中使用ajax上传图像并存储在数据库中
- math - 如何根据点计算圆的起点和终点
- javascript - 根据单数或复数添加后缀
- excel - With函数VBA中的多对象表达式
- javascript - 用于验证字符串的正则表达式,确保单词仅由一个特殊符号分隔
- c++ - 初始化用户定义类的指针向量
- wpf - 自定义控件在xaml中使用时如何设置DP值?(声明时)
- sql - 在透视 xml 后将 xmltype 解析为表
- flutter - 找不到提供程序 - Flutter
- power-automate - 使用 MS Flow 在 Microsoft Teams 上未呈现自适应卡片图像