javascript - 如何创建多种类型的集合并将它们与 Typescript 中的类型一起使用?
问题描述
我有 2 种自定义类型,Graphic
并且Asset
我希望将它们放在同一个数组中。我希望能够访问它们并访问它们的类型信息。
const trail: Array<Graphic | Asset> = [];
for (let index = 0; index < this.props.graphics.length; index++) {
const graphic = this.props.graphics[index];
trail.push(graphic);
if (index <= this.assets.length - 1) trail.push(this.assets[index]);
}
// this doesn't work, .artist does not exist on type Graphic | Asset
if (typeof trail[0].artist != "undefined") {
}
我认为以下类型的方法可以工作,但我还没有找到方法。
enum TrailType {
Graphic,
Asset
}
interface Trail {
type: TrailType
element: Graphic | Asset
}
只有当类型共享至少一个属性时才可能这样做?
解决方案
是的,您需要有某种方式来定义类型是什么。它被称为discrimanted union
. 你可以在这里阅读https://medium.com/@ahsan.ayaz/understanding-discriminated-unions-in-typescript-1ccc0e053cf5#:~:text=The%20discriminant%20is%20a%20singleton,the%20discriminant% 20或%20the%20标签。
在您的情况下,它将按以下方式显示。
interface GraphicTrail {
type: TrailType.Graphic,
element: Graphic
}
interface AssetTrail {
type: TrailType.Asset,
element: Asset
}
type Trail = GraphicTrail | AssetTrail
现在您可以if
检查以验证您正在使用哪种类型,因此 Typescript 将能够缩小变量的类型。
另一种解决方案是type guard
。例如。
function isGraphic(data: Graphic | Asset): data is Graphic {
return Boolean(data.someFieldsThatExistsOnGraphicOnly); // Here any boolean expression that you fill confident with will work.
}
推荐阅读
- mysql - 如何在 where 子句中使用 if-else
- node.js - Firebase Cloud Function Keep 返回“请求失败,状态码 404”
- wordpress - Woocommerce 钩子:如何在主页的特色产品中添加内容?
- visual-studio-code - 如何知道“您信任此文件夹中文件的作者吗?”的文件夹名称或路径
- reactjs - 反应:特殊字符未正确显示
- php - 当我从 laravel 本地上传时,数字海洋 403 被禁止
- javascript - 如何添加用 javascript
- arrays - AsStreams FireDAC 从 MemoryStream 获得 nil 值
- clang - 在 VS 2019 中链接 dpdk 应用程序时出错 - 在哪里可以找到丢失的 per_lcore__lcore_id 符号
- spring-boot - 从数据库中选择查询记录是否需要使用实体注释