Typescript - 属性的允许值

48

在Typescript中,仅允许为属性设置特定值的最佳方法是什么?

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

    constructor() {}
}

我希望将这些类型设为唯一允许的类型,以防我在扩展Foo类时输入错误的类型。

3个回答

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

    constructor() {}
}
或者。
type MyType = "foo1" | "foo2" | "foo3";

class Foo {
    public type: MyType;

    constructor() {}
}

但这仅在编译时执行,而不是在运行时执行。
如果您希望确保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;
    }
}

这被称为字符串文字类型


5
const TYPES = ['a', 'b', 'c'] as const; // TS3.4 syntax
type yourType = typeof TYPES[number]; // 'a'|'b'|'c';

4
尽管这段代码可能解决问题,但好的答案应该解释代码做了什么以及如何帮助解决问题。 - BDL
as const 是什么?为什么需要它? - Kartik Shah
1
@KartikShah 如果没有 typeof TYPES[number],它将被解析为一个字符串数组。 const TYPES = ['a', 'b', 'c']; type yourType = typeof TYPES[number]; // string;const TYPES = ['a', 'b', 'c'] as const; type yourType = typeof TYPES[number]; // 'a'|'b'|'c';更多信息可以在 TS 文档中找到 -> https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions - Gynekolog

3
你可以使用“枚举”:
enum MyType {
  Foo1 = 'foo1',
  Foo2 = 'foo2',
}

class FooClass {
  private foo: MyType;

  constructor(foo: MyType) {
    this.foo = foo;
  }
}

let bar = new FooClass(MyType.Foo2);

Typescript文档


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接