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 👹
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:
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:
- Discriminated unions
- The in operator
- Type guards
- Assertion functions