typescript - 如何表示可以是多种类型的数据
问题描述
假设我有一个对象数组,其中“值”可以是不同的类型,我天真地表示为:
interface Attribute {
attribute: string;
value: Date | string | string[];
}
[
{
attribute: 'date',
value: new Date('2020-01-01')
},
{
attribute: 'tags',
value: ['foo', 'bar']
}
{
attribute: 'name',
value: 'Foo'
}
]
我想知道是否有更好的方法来表示这些数据:
有什么“属性”是动态的,这就是为什么它们被表示为可以具有多种值类型的对象数组的原因。
我需要用不同类型的值做不同的事情:例如,如果我遇到一个带有字符串数组值的对象,我需要能够将字符串推送给它。如果我遇到带有日期的对象,我需要能够以正确的日期格式等显示它。
所以我要么需要使用类型保护,要么为每个对象添加一个“类型”属性并基于它进行强制转换:
{
attribute: 'tags',
value: ['foo', 'bar'],
type: Type.StringArray
}
if (attribute.type === Type.StringArray) {
return (attribute.value as string[]).join(', ');
}
或者我也许可以用这种方式表示事物以避免需要转换:
{
attribute: 'tags',
stringArrayValue: ['foo', 'bar'],
stringValue: undefined,
dateValue: undefined
}
有更好的选择吗?
解决方案
interface TagsAttribute {
attribute: 'tags';
value: string[];
}
interface DateAttribute {
attribute: 'date';
value: Date;
}
interface NameAttribute {
attribute: 'name';
value: string;
}
type Attribute = TagAttribute | DateAttribute | NameAttribute;
Attribute
类型称为判别联合,attribute
属性是判别式。
推荐阅读
- c - 读取访问中断:树为 0xAE0A74BF
- node.js - 浏览 Docker 托管的应用程序时出现 ERR_CONNECTION_REFUSED
- r - 不同年份的滚动计数
- python - 在 linux 的 windows 子系统上运行时的 time.clock() 精确规范
- c++ - 我的代码仅适用于一个输入。请指教
- java - Android 在 Cordova 插件中使用自定义依赖项?
- java - 在任何地方解析文本的 XML 文档
- reactjs - ReactJS componentDidUpdate() prevState 等于 currentState
- oracle - 仅使用第一列的多列索引
- sockets - ZeroMQ 套接字在 goroutine 中不接收数据