Typescript - 属性的允许值

big*_*est 21 typescript

在Typescript中最好的方法是只允许属性的多个值?

class Foo {
    public type:string;
    // Possible values for type: ['foo1', 'foo2', 'foo3']

    constructor() {}
}
Run Code Online (Sandbox Code Playgroud)

我想让这些类型成为唯一允许的类型,防止我在扩展Foo类时输入错误的类型.

Nit*_*mer 41

class Foo {
    public type: "foo1" | "foo2" | "foo3";

    constructor() {}
}
Run Code Online (Sandbox Code Playgroud)

要么

type MyType = "foo1" | "foo2" | "foo3";

class Foo {
    public type: MyType;

    constructor() {}
}
Run Code Online (Sandbox Code Playgroud)

但这仅在编译时强制执行,而不是在运行时执行.
如果要确保值Foo.type只是其中一个值,则需要在运行时检查:

type MyType = "foo1" | "foo2" | "foo3";

class Foo {
    public type: MyType;

    constructor() {}

    setType(type: MyType): void {
        if (["foo1", "foo2", "foo3"].indexOf(type) < 0) {
            throw new Error(`${ type } is not allowed`);
        }

        this.type = type;
    }
}
Run Code Online (Sandbox Code Playgroud)

这称为字符串文字类型.


use*_*949 5

const TYPES = ['a', 'b', 'c'] as const; // TS3.4 syntax
type yourType = typeof TYPES[number]; // 'a'|'b'|'c';
Run Code Online (Sandbox Code Playgroud)

  • 尽管此代码可能会解决问题,但一个好的答案应该解释该代码的**什么**以及它**如何**提供帮助。 (6认同)