StephenRios StephenRios - 1 year ago 67
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 Source

The syntax is

export class customClass {

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


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download