Sub topic 4
Narrowing `unknown` with `typeof`, `instanceof`, and `in`
Assume you know basic TypeScript annotations, interfaces, union types, and JavaScript’s typeof, instanceof, and try/catch. This chapter uses TypeScript 4.9 or later.
The unknown type can hold any value, but TypeScript does not let you use that value until you prove what it is. This proof is called narrowing. A narrowing check reduces a broad type such as unknown to a more specific type inside a block.
function describe(value: unknown): string {
if (typeof value === "string") {
return `text with ${value.length} characters`;
}
if (typeof value === "number") {
return `number: ${value}`;
}
return "something else";
}
console.log(describe("hello"));
console.log(describe(42));
console.log(describe(true));Before the first if, value is unknown. Inside the first block, TypeScript knows that it is a string. Inside the second block, it knows that it is a number.
Use `typeof` for primitive values
The typeof operator checks JavaScript’s primitive categories:
| Check | Narrowed type |
|---|---|
| `typeof value === "string"` | `string` |
| `typeof value === "number"` | `number` |
| `typeof value === "boolean"` | `boolean` |
| `typeof value === "bigint"` | `bigint` |
| `typeof value === "symbol"` | `symbol` |
| `typeof value === "function"` | function |
| `typeof value === "object"` | object or `null` |
Two JavaScript behaviors often cause errors:
typeof nullis"object", even thoughnullis not a usable object.- Arrays also produce
"object".
Check for null when you need a real object.
function objectKeys(value: unknown): string[] {
if (typeof value === "object" && value !== null) {
return Object.keys(value);
}
return [];
}A typeof check does not tell TypeScript the properties of an object. For that, use in.
Use `in` to check object properties
The in operator checks whether a property exists on an object. Combine it with an object and null check before using it on unknown.
function getName(value: unknown): string | undefined {
if (
typeof value === "object" &&
value !== null &&
"name" in value &&
typeof value.name === "string"
) {
return value.name;
}
return undefined;
}
console.log(getName({ name: "Ada" }));
console.log(getName({ name: 42 }));The first in check shows that the property exists. The second check proves that the property has the expected type. Property existence alone does not validate the value.
Use `instanceof` for class instances
instanceof checks whether an object was created by a particular class or constructor. It is especially useful for caught errors.
function errorMessage(value: unknown): string {
if (value instanceof Error) {
return value.message;
}
return String(value);
}
try {
JSON.parse("{");
} catch (error: unknown) {
console.error(errorMessage(error));
}After error instanceof Error, TypeScript allows access to message, name, and other Error properties.
instanceof is not a general interface validator. An interface exists only during compilation, so this is invalid:
// interface User { name: string }
// value instanceof User; // Error: User is not a runtime valueUse typeof and in checks to validate object-shaped data. Use instanceof when you have a runtime constructor, such as Error, Date, or a class you defined.
Common narrowing mistakes
- Calling a property before checking that the value is an object.
- Forgetting
value !== nullaftertypeof value === "object". - Treating an array as a record without checking
Array.isArray(value). - Assuming
instanceof Errorcatches every error from another JavaScript realm. Errors crossing workers or frames may need a fallback such asString(value). - Using a type assertion to silence an error instead of checking the value.
Exercise
Write a function that returns the length of an unknown value when it is a string or an array, and returns 0 for every other value.
Show answer
function lengthOf(value: unknown): number { if (typeof value === "string") { return value.length; } if (Array.isArray(value)) { return value.length; } return 0; }