TypeScript 联合类型数字或特定字符串

ulv*_*ked 2 types typescript typescript2.0 union-types

我正在尝试 typeScript 联合类型。我有一个带有数字属性的类,但我希望它具有三种特殊情况:Infinity、None 和 Auto

Infinity 和 None 可以分别用Number.POSITIVE_INFINITY和表示NULL,但我不知道如何处理自动值。

该值最初出现在表示为字符串的 XML 文档中。例如<element myValue="123"/> <element myValue="-4096"/> <element myValue="infinity"/> <element myValue="auto"/><element/>

如何创建一个可以用作数字但仍然具有可用 auto 值的联合类型。我考虑过使用数字和枚举的联合类型,但我不确定如何充分利用它。

有小费吗?

class MyClass {
    name: string;
    duration: number; // Want to support None/Null, Infinity and Auto
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*Liu 5

'auto'考虑在类型注释中使用字符串文字:

class MyClass {
    name: string;
    duration: number | undefined | 'auto';
}
Run Code Online (Sandbox Code Playgroud)

(这里我使用undefined代替来null表示缺失值。如果您尚未使用 TypeScript 2.0,请省略undefined。)

此类型注释允许您分配数字(包括Number.POSITIVE_INFINITY)、undefined'auto'to duration,但不能分配任何其他字符串。

使用示例:

var c = new MyClass();
// ...

if (c.duration === undefined) {
    // ...
} else if (c.duration === 'auto') {
    // ...
} else {
    // In this branch, the type of c.duration will be number.
    // ...
}
Run Code Online (Sandbox Code Playgroud)