StephenRios StephenRios - 1 month ago 9
TypeScript Question

Creating value restrictions on class values

So in typescript we can declare a custom class like so:

export class customClass {
username: string;
}


What I am looking to do is implement on a restriction on the values that username can hold. Sort of like a white list so that it can only be set to specific values like:

export class customClass {
username: string["bob","sam","george"];
}


would mean the username could only be set to "bob" "sam" or "george". Which is clearly not what this syntax does (and in fact is broken), but this is the functionality I am looking for.

I cannot find documentation anywhere as to whether or not this is possible.

Answer

The syntax is

export class customClass {

    username: "bob" | "sam" | "george";

}

It's a combination of string literal types with union type.