Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerate TypeScript string literals

Tags:

typescript

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")
}
like image 862
Ralph Avatar asked Jan 19 '17 18:01

Ralph


People also ask

What are string literals in TypeScript?

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.

Which is the string literal?

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.

How do you define a string constant in TypeScript?

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.

Is not assignable to type string?

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.


1 Answers

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' ]
like image 152
artem Avatar answered Oct 06 '22 18:10

artem