Typescript 4.1: Template literal types, computed property names, and more

24th January 2021

Typescript 4.1 adds support for template literal types. This, along with the new utility types, unlocks computed property names, simple getter-setter interfaces and more.

type Foo = 'a' | 'b' | 'c';
// Bar = 'a-template' | 'b-template' | 'c-template'
type Bar = `${Foo}-template`;

In addition, a number of new utility types have been introduced:

type A = Uppercase<'MixedCase'>; // 'MIXEDCASE'
type B = Lowercase<'MixedCase'>; // 'mixedcase'
type C = Capitalize<'MixedCase'>; // 'MixedCase'
type D = Uncapitalize<'MixedCase'>; // 'mixedCase'

Combining the above with the as keyword makes creating Redux-like functionality with strict types a breeze.

type State = {
    foo: string;
    bar: number;
}

/**
 * Actions = {
 *   setFoo: (state: State, value: string) => void;
 *   setBar: (state: State, value: number) => void;
 * }
 */
type Actions = {
  [K in keyof State & string as `set${Capitalize<K>}`]: (state: State, value: State[K]) => void;
}