首页 > 解决方案 > 如何表示可以是多种类型的数据

问题描述

假设我有一个对象数组,其中“值”可以是不同的类型,我天真地表示为:

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
}

有更好的选择吗?

标签: typescript

解决方案


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属性是判别式。


推荐阅读