[Typescript] Literal Type
Literal Type
works similarly to enums in Java.
you can specify a type and a specific value at once, as shown below.
literal type
let dir:"LEFT";
- string type, only accepting the value "LEFT"
only the string "LEFT"
can be bound to this variable.
literal type
let dir:"LEFT";
dir = "left"; // #ERROR
dir = "Left"; // #ERROR
dir = "LEFT"; // #SUCCESS
rather than being used alone, this odd type is used to function like an enum in Java, with the shape
when Java only accepts one of three values, it looks like this
JAVApublic enum Dir {
LEFT,
CENTER,
RIGHT
}
in Typescript, this would look like this
JAVASCRIPTlet dir = "LEFT"|"CENTER"|"RIGHT";
- only three strings are allowed in the variable dir
alternatively, you can declare it as a separate type.
JAVASCRIPTtype Dir = "LEFT"|"CENTER"|"RIGHT"; // declare separate type
let where:Dir; // restricted to the type Dir
- the variable
where
can only contain one of the strings"LEFT"
,"CENTER"
, or"RIGHT"