Estimate project
← All posts

4 Lesser-Known TypeScript Tips That Will Make Your Developer Experience Better

TypeScript offers much more than type annotations on function arguments. This blog post presents interesting applications of less popular TypeScript techniques and features, including type-level programming, generics and branded types.

11 min read
typescriptReacttype-level programming

TypeScript offers much more than type annotations on function arguments. In this post we’ll explore some interesting applications of less popular TypeScript techniques and features, including type-level programming, generics and branded types.

1. Derive new types instead of copy-pasting where possible

Imagine our app handles transactions and supports 3 currencies. To type our utility functions more precisely, we might define a union type of those currencies:

type Currency = "EUR" | "USD" | "GBP";

function currencyToSymbol(currency: Currency): string {
    switch (currency) {
      case "EUR":
        return "€";
      case "USD":
        return "$";
      case "GBP":
        return "£";
    }
  }

So far everything is fine. With this type we get handy autocompletion, and TypeScript makes sure every possible case is covered. Trouble starts when we need a UI element that lets the user pick a currency:

const CurrencySelector = () => (
    <select>
      {["EUR", "USD", "GBP"].map((currency) => (
        <option value={currency}>{currency}</option>
      ))}
    </select>
  );

That’s far from perfect. We might move the tuple out of the component and type it as Currency[], but we would still have to keep it in sync with the Currency type by hand whenever it changes. All of these issues go away once we simply derive the Currency type from a constant tuple:

const currencies = ["EUR", "USD", "PLN"] as const;
type Currency = typeof currencies[number];
//   ^ "EUR" | "USD" | "PLN"

Type-level programming

All right, let’s try something harder.

Imagine an API that returns a response of this type:

type RawResponse = {
  last_edit: string;
  items: {
    content: string;
    column_idx: number;
    selected_color: string;
  }[];
}

Our app, however, uses camelCase, so we map the response onto a new object with matching field names:

type Response = {
  lastEdit: string;
  items: {
    content: string;
    columnIdx: number;
    selectedColor: string;
  }[];
}

const mapResponseToCamelCase = (resp: RawResponse): Response => {
// ...
}

This approach comes with plenty of downsides. The most apparent is the boring chore of converting and writing out this type by hand – something programmers try to avoid. We could have an AI do it, but that would introduce a different issue: redundancy. Whenever the API changes, we’d need to remember to update the type in two places.

TypeScript’s powerful support for type-level programming can fix all of this. Let’s write a type that accepts any snake case type and turns it into its camel case equivalent:

type SnakeToCamel<T> = T extends `${infer part}_${infer Rest}`
    ? `${part}${Capitalize<SnakeToCamel<Rest>>}`
    : T;

type example1 = SnakeToCamel<"hello">; // "hello"
type example2 = SnakeToCamel<"hello_world">; // "helloWorld"

type DeepSnakeToCamel<T> = T extends any[]
    ? { [K in keyof T]: DeepSnakeToCamel<T[K]> }
    : {
        [K in keyof T as SnakeToCamel<K>]: DeepSnakeToCamel<
          T[K]
        >;
      };

type example3 = DeepSnakeToCamel<{
    foo: { foo_bar: string; foo_bar_baz?: { bar: string } };
  }>;
/*   ^
 {
    foo: {
        fooBar: string;
        fooBarBaz?: {
            bar: string;
        };
    };
}
*/

From now on, RawResponse can serve as the single source of truth, with other types derived from it:

type Response = DeepSnakeToCamel<RawResponse>;

const mapResponseToCamelCase = (resp: RawResponse): Response = {
// ...
}

Using TypeScript’s built-in types

Below are a few more built-in generic types that come in handy for deriving other types:

  • Awaited – unwraps Promises recursively, e.g. Awaited<Promise<string>> -> string
type unwrapped = Awaited<Promise<string>>;
//   ^ string
  • Pick and Omit – select or leave out a set of properties of another type, for example:
type BlogPost = {
  title: string;
  author: Author;
  content: string;
}

type BlogPostPreview = Pick<BlogPost, "title" | "author">
//   ^ { title: string; author: Author; }
// same as:
type BlogPostPreview2 = Omit<BlogPost, "content">;
  • Exclude and Extract – select or leave out members of a union, for example:
type A = Exclude<"a" | "b" | "c", "a" | "b">;
//   ^ "c"

type B = Extract<"a" | "b" | "c", "a" | "f">;
//   ^ "a"
  • Parameters and ReturnValue – pull out, respectively, the types of a function’s parameters or of its return value, for example:
type params = Parameters<(a: string, b: number) => void>;
//   ^ [string, number]

type retVal = ReturnValue<(a: string, b: number) => void>;
//   ^ void

2. Generate types directly from your backend

How can we make communication with external REST APIs type-safe?

For small projects, or when the REST API is simple and stays unchanged, typing the fetch functions ourselves is fine. In a project under active development, though, it gets tiresome to update the API types by hand based on change logs or – even worse – slack messages from teammates.

Code generation is one way out. A typical workflow looks like this:

  • The backend team hands us an OpenAPI schema in a JSON or Yaml file, typically generated from their source code.
  • The frontend team regenerates the types with a tool such as openapi-typescript or dtsgenerator.
  • Lastly, they run a type check to find any breaking changes that need fixing.

Generating fully typed React hooks

When you use React together with react-query, you can take it a step further and generate not only types but fully-typed react-query hooks as well! 🤯 For this I can recommend openapi-codegen:

import { useListPets } from "./petStore/petStoreComponents"; // <- output from openapi-codegen

const Example = () => {
  const { data, loading, error } = useListPets();

  // `data` is fully typed and have all documentation from OpenAPI
};

More details can be found in this blog post.

Naturally, everything hinges on how good the OpenAPI schema is. If it relies only on broad types (for instance string rather than “option1” | “option2”) or doesn’t separate required fields from optional ones, most of the advantages are lost.

3. Branded types

Our applications sometimes work with values that form specific subsets of a built-in primitive type. Emails, urls or particular ID formats, for example, are subsets of the string type, while odd numbers, integers or primes are subsets of the number type. Expressive as the TypeScript type system is, it too has limits :)

The problem

Let’s say we’re building a program that works with prime numbers. To keep it readable, we’ve written several small helper functions that accept a prime as an argument and perform some calculations on it. Looking at the program as a whole, though, we read one prime and then pass it through these functions.

const doStuffWithPrime1 = (prime: number) => { /* ... */ }
const doStuffWithPrime2 = (prime: number) => { /* ... */ }
const doStuffWithPrime3 = (prime: number) => { /* ... */ }

const main = (arg: number) => {
    const res1 = doStuffWithPrime1(arg);
    const res2 = doStuffWithPrime2(arg);
    const res3 = doStuffWithPrime3(arg);

    console.log("results: ", res1, res2, res3);
}

Types alone can’t guarantee that the argument really is a prime. Two simple solutions come to mind:

  1. Put assertions (isPrime) at the start of every function.
  2. Check once in main that arg is prime and let the helper functions “trust” that they receive a prime number.

The advantage of the first option is that the program stays safe however we rearrange the code around these helpers. It also keeps the helper functions pure and reusable, because their correctness doesn’t rely on an assumption that cannot be verified at compile time.

The second option, on the other hand, spares us redundant assertions, which here could be fairly expensive to compute.

So what if I told you that a less popular TypeScript technique lets us get the advantages of both approaches at once? 😊

Solving the problem with branded types

In TypeScript, defining a Prime type as type Prime = number produces nothing more than an alias that can’t be told apart from the type on the right-hand side. That means Prime can be used wherever a number is expected, and the other way round.

type Prime = number;

declare function fun(p: Prime): void;

// this should error but it doesn't
const someNum: number = 2;
fun(someNum); 
fun(42);

If we instead write:

type Prime = number & { readonly _brand: unique symbol };

we get a distinct type tied to that specific Prime type identifier.

type Prime = number & { readonly _brand: unique symbol };

declare function fun(p: Prime): void;

const someNum: number = 2;
fun(someNum); // this results in TS error 🥳
fun(42); // this as well

Next, we can write an assertion function that verifies whether a number is prime and expresses that at the type level:

function assertIsPrime (num: number): asserts num is Prime {
    /* put real implementation here... */
    if (num !== 2) {
        throw new Error("the number is not prime");
    }
}

const someNum: number = 2;

assertIsPrime(someNum); // after this line someNum will be inferred to be `Prime`

fun(someNum); // it type checks!

fun(2); // this errors, because `2` is inferred as number so it can't be passed
        // to a function that requires an argument of `Prime` type 👍🏻

Our initial example can now be rewritten with branded types:

type Prime = number & { readonly _brand: unique symbol };

function assertIsPrime (num: number): asserts num is Prime {
    /* put real implementation here... */
    if (num !== 2) {
        throw new Error("the number is not prime");
    }
}

const doStuffWithPrime1 = (prime: Prime) => { /* ... */ }
const doStuffWithPrime2 = (prime: Prime) => { /* ... */ }
const doStuffWithPrime3 = (prime: Prime) => { /* ... */ }

const main = (arg: number) => {
    assertIsPrime(arg);
    const res1 = doStuffWithPrime1(arg);
    const res2 = doStuffWithPrime2(arg);
    const res3 = doStuffWithPrime3(arg);

    console.log("results: ", res1, res2, res3);
}

4. Use generics in React components

Suppose our app contains these two types:

type User = {
  id: string;
  name: string;
  role: 'admin' | 'client';
  joinedAt: Date;
};

type Item = {
  id: string;
  name: string;
  size: 'small' | 'medium' | 'large';
};

In some parts of the app we need to show a list of users, and in others a list of items. We could write separate UsersList and ItemsListcomponents, but since both lists look and behave identically, a different approach may be better. One option is a single component that takes anything having a name and an id:

type ListProps = {
  options: { name: string; id: string }[];
  onChange: (x: { name: string; id: string }) => void;
};

const List = ({ options, onChange }: ListProps) => {
  return (
    <select
      onChange={(e) => onChange(options.find((el) => el.id === e.target.value))}
    >
      {options.map((el) => (
        <option value={el.id}>{el.name}</option>
      ))}
    </select>
  );
};

Because both types contain these two fields, either can be passed to the List component, and it appears to work.

const users: User[] = [
  {
    id: 'aaa',
    name: 'John',
    role: 'admin',
    joinedAt: new Date(2023, 5, 7),
  },
  {
    id: 'bbb',
    name: 'Mark',
    role: 'client',
    joinedAt: new Date(2023, 5, 7),
  },
  {
    id: 'ccc',
    name: 'Matt',
    role: 'client',
    joinedAt: new Date(2023, 5, 7),
  },
];

const items: Item[] = [
  {
    id: 'ddd',
    name: 'Table',
    size: 'small',
  },
  {
    id: 'eee',
    name: 'Chair',
    size: 'medium',
  },
  {
    id: 'fff',
    name: 'Bed',
    size: 'large',
  },
];

export default function App() {
  return (
    <div>
      <h1>Hello</h1>
      <List options={users} onChange={(x) => console.log(x)} />
      <List options={items} onChange={(x) => console.log(x)} />
    </div>
  );
}

Sadly, there’s a catch. No matter what we pass to the component, the argument of its onChange is always typed as { id: string; name: string; }, even though we know its actual type.

Programmers can reach for as in such cases to tell the compiler “I know better than you”. That, however, adds verbosity, and if the implementation changes later, we could end up with a runtime error.

export default function App() {
  return (
    <div>
      <h1>Hello</h1>
      <List options={users} onChange={(x) => someOperationOnUser(x as User)} />
      <List options={items} onChange={(x) => someOperationOnItem(x as Item)} />
    </div>
  );
}

Luckily, TypeScript’s generics let us make this component behave exactly as intended.

To start, we declare a type variable T that may be any type, provided it extends the { id: string; name: string } shape – that is, it contains at least these two fields but may contain more.

const GenericList = <T extends { id: string; name: string }>(...) => {
  ...
};

Then we pass T into GenericListsProps to link the type of the options prop to onChange. In this way we express that, whatever T turns out to be, options is an array of it and onChange is a function from T to void.

type GenericListProps<T> = {
  options: T[];
  onChange: (x: T) => void;
};

const GenericList = <T extends { id: string; name: string }>({
  options,
  onChange,
}: GenericListProps<T>) => {
    ...
};

The component’s body stays unchanged. Let’s now use the component in our app and watch how the types get inferred!

type GenericListProps<T> = {
  options: T[];
  onChange: (x: T) => void;
};

const GenericList = <T extends { id: string; name: string }>({
  options,
  onChange,
}: GenericListProps<T>) => {
  return (
    <select
      onChange={(e) => onChange(options.find((el) => el.id === e.target.value))}
    >
      {options.map((el) => (
        <option value={el.id}>{el.name}</option>
      ))}
    </select>
  );
};

Thank you for reading! Was any of these techniques especially interesting to you? Do you rely on them in your everyday coding? Tell us, and subscribe to our blog for more front-end posts to come.