2.9 String literal types

A string literal types can help us to create string enumerations and eliminate some scenarios in which typos in hard coded strings could lead to run time issues.

Getting Ready

All you need to be able to use union types is an installation of TypeScript 2.0 or higher.

How to do it…

A string literal type is a type whose expected value is a string with textual contents equal to that of the string literal type:

type ok = 'ok';

How it works…

A string literal type can be considered a subtype of the string type. This means that a string literal type is assignable to a plain string, but not vice-versa:

// Ok
const a: ok = 'ok';
const b: 'ok' = a;
const c: string = a; 

// Error
const a: ok = 'no';
const a: ok = c;

There’s more…

We can use string literal types in combination with union types to create string enumerations:

type result = 'ok' | 'fail' | 'abort';

Once you have declared a string literal type, it can be used as a normal type:

function compute(n: number): result {
    if(...) {
      return 'ok';
    } else if (...) {
      return 'fail';
    } else {
      return 'abort'; // error

Note how the string literal type is useful to prevent a runtime error caused by a magic string.

Source Code

String literal types

See also

Please refer to the recipe about Specialized overloading signatures in this chapter to learn how to use string literals to overload function signatures.

Shiv Kushwaha