Back to all questions

What is Type Narrowing in TypeScript?

Devs Hive

Devs Hive

Seen on interview: 1 user

This is a very common question in TypeScript conversations. If you hear it in an interview, it can be a good sign that TS is used in the project for real, not just for show.

Type Narrowing means refining a type for TypeScript. For example, we have a variable of type string | number, and narrowing in this case means checking whether the variable's value is string or number. Depending on the actual value, we will have a different implementation for each data type.

There are several ways to narrow a type. In the context of this question, we will cover only the basic ones that are usually asked about in interviews:

typeof

This is the simplest approach, used for primitives. When TypeScript encounters a Union type, it does not allow you to call methods or access properties that exist in only one of the types. In that case, you need to explicitly check that the value is a specific type. Or you could use as, but that is considered Bad Practice in TypeScript 👹

function format(value: string | number): string {
/**
* toUpperCase доступний тільки в string тому TS видасть помилку,
* якщо ми захочемо викликати його. Щоб викликати метод, TS має впевнитись
* що тип дійсно string, для цього ми використовуємо typeof. Це і є звуження типів
* */
if (typeof value === "string") {
return value.toUpperCase();
}
// Якщо тип не string, значить він number i для value доступні всі поля і методи
return value.toFixed(2);
}

instanceof

This is type narrowing by checking whether an object is an instance of a particular class. It is not used as often as, for example, typeof, but to understand Type Narrowing you need to cover it too. A typical use case is error handling:

class NotFoundError extends Error {
constructor(public resource: string) {
super("Not found");
}
}

const handleError = (e: unknown) => {
// В цьому випадку Type Narrowing допомагає нам по різному опрацьовувати
// HTTP помилки, які є класами. Також, unknown забовʼязує нас зробити type narrowing
// перед використанням полів чи методів
if (e instanceof NotFoundError) {
console.log(`Missing: ${e.resource}`);
}

if (e instanceof Error) {
console.log(e.message);
return;
}

console.log("Unknown error");
}

Usually, understanding typeof and instanceof is quite enough for an interview. But if you want to dig a bit deeper, here are other ways of Type Narrowing:

  1. Discriminated unions
  2. The in operator
  3. Type guards
  4. Assertion functions

Seen on interview?

Comments (0)

Sign in to leave a comment

No comments yet. Be the first!