Typescript – Allowed values for a property

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

    constructor() {}
}

or

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

class Foo {
    public type: MyType;

    constructor() {}
}

But this is enforced only in compilation, and not in run time.
If you want to make sure that the value of Foo.type is only one of those values then you need to check that at runtime:

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;
    }
}

This is called String Literal Types.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)