Lesser-Known TypeScript Types

Covers never, ArrayLike, and PromiseLike, when to use them, and links to further reading.

Sep 5, 2021 · 2 min read · 263 Words · -Views -Comments · Programming
TypeScript 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

TypeScript is now the default in many teams. Types act as documentation and safety nets. Still, some types aren’t used often—I didn’t truly understand them until I dug deeper. Here are a few worth noting.

never

Key points:

  1. never is the bottom type.
  2. It’s useful in exhaustive checks to ensure new cases aren’t forgotten.
  3. void means a function returns undefined; never means it never returns.

Example:

interface Circle {
  kind: 'circle';
  radius: number;
}

interface Square {
  kind: 'square';
  sideLength: number;
}

type Shape = Circle | Square;

function getArea(shape: Shape) {
  switch (shape.kind) {
    case 'circle':
      return Math.PI * shape.radius ** 2;
    case 'square':
      return shape.sideLength ** 2;
    default:
      const exhaustiveCheck: never = shape;
      return exhaustiveCheck;
  }
}

If you later add Triangle to Shape, the assignment to never fails, reminding you to update the switch.

Further reading:

ArrayLike, PromiseLike

TypeScript’s lib definitions include “like” types. ArrayLike<T> differs from Array<T>:

interface ArrayLike<T> {
  readonly length: number;
  readonly [n: number]: T;
}

interface Array<T> {
  length: number;
  toString(): string;
  pop(): T | undefined;
  // ...
}

ArrayLike only requires an indexed collection with a length. Array has full methods like pop.

Example:

function getSize(arr: ArrayLike<any>): number {
  return arr.length;
}

console.log(getSize([1, 2, 3])); // ok

function fn() {
  console.log(getSize(arguments)); // ok with ArrayLike; would fail with Array
}

Useful for arguments or DOM collections that aren’t real arrays.

More info: https://stackoverflow.com/questions/43712705/why-does-typescript-use-like-types

Closing Thoughts

If you only ever use interface, Pick, Omit, and unions, you’re missing a lot of TypeScript’s power. Learn these niche types to write more expressive, safer code.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover