Is there any way to loop over the values of a TypeScript string literal?
type category = "foo" | "bar" | "baz" | "xyzzy"
for (c in category) {
// ... do something with each category
}
I currently have something like this:
let cat: category = ...
switch (cat) {
case "foo":
default:
process("foo")
break
case "bar":
process("bar")
break
case "baz":
process("baz")
break
case "xyzzy":
process("xyzzy")
break
}
but I would rather use something like
let others: category = []
for (c in category) { // Iterate over possible category values
if (c !== "foo") others.push(c)
}
if (others.indexOf(cat) >= 0) {
process(cat)
} else {
process("foo")
}
The string literal type allows you to specify a set of possible string values for a variable, only those string values can be assigned to a variable. TypeScript throws a compile-time error if one tries to assign a value to the variable that isn't defined by the string literal type.
A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string. You must always prefix wide-string literals with the letter L.
Typescript constants are variables, whose values cannot be modified. We declare them using the keyword const . They are block-scoped just like the let keyword. Their value cannot be changed neither they can be redeclared.
The "Type 'string' is not assignable to type" TypeScript error occurs when we try to assign a value of type string to something that expects a different type, e.g. a more specific string literal type or an enum. To solve the error use a const or a type assertion.
With typescript 2.1 and keyof type, it's possible to do it the other way round - you can define an object with necessary keys, and get union type of all the keys using keyof
:
let categoryKeys = {foo: '', bar: '', baz: '', xyzzy: ''}; // values do not matter
type category = keyof typeof categoryKeys;
let x: category = 'foo'; // ok
let z: category = 'z'; // error TS2322: Type '"z"' is not assignable
// to type '"foo" | "bar" | "baz" | "xyzzy"'.
console.log(Object.keys(categoryKeys)); // prints [ 'foo', 'bar', 'baz', 'xyzzy' ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With