Sub topic 4
Narrowing unknown with typeof, instanceof, and in
What you need before this chapter
This chapter assumes you can read basic TypeScript: type annotations, interfaces, and union types. It also assumes you know how typeof, instanceof, and try/catch work in JavaScript. You should be able to run tsc or use an editor that shows TypeScript errors. The examples use TypeScript 4.9 or later, because that version improved how in narrows.
Why unknown needs narrowing
A value of type unknown can be anything, so TypeScript lets you do almost nothing with it. You can assign it to another unknown or any, compare it with ===, and pass it to a function that accepts unknown. Reading a property, calling it, or doing arithmetic on it is an error.
Narrowing is the compiler's way of shrinking a type inside a branch of code. You write a runtime check, and TypeScript reasons that if the check passed, the value must have a more specific type. Three checks do most of the work with unknown: typeof, instanceof, and in.
Narrowing with typeof
The typeof operator returns one of a fixed set of strings. TypeScript recognizes each comparison and narrows unknown to the matching type.
| typeof result | Narrowed type | Column |
|---|---|---|
| `"string"` | `string` | |
| `"number"` | `number` | |
| `"bigint"` | `bigint` | |
| `"boolean"` | `boolean` | |
| `"symbol"` | `symbol` | |
| `"undefined"` | `undefined` | |
| `"function"` | `Function` | |
| `"object"` | `object \ | null` |
The last row matters most. In JavaScript, typeof null is "object", so a typeof check for objects also lets null through. TypeScript models this honestly, and you must rule out null before reading properties.
The function below classifies any value. Each early return removes a possibility, so the type shrinks as the function proceeds.
function describe(value: unknown): string {
if (typeof value === "string") return `string of length ${value.length}`;
if (typeof value === "number") {
return Number.isNaN(value) ? "NaN" : `number ${value.toFixed(2)}`;
}
if (typeof value === "boolean") return value ? "true" : "false";
if (typeof value === "bigint") return `bigint ${value}`;
if (typeof value === "undefined") return "undefined";
if (typeof value === "function") return "function";
if (value === null) return "null";
if (Array.isArray(value)) return `array of ${value.length}`;
if (typeof value === "object") return "object";
return "symbol";
}
console.log(describe("hello")); // string of length 5
console.log(describe(3.14159)); // number 3.14
console.log(describe(null)); // null
console.log(describe([1, 2])); // array of 2
console.log(describe({})); // objectThree details are worth noting. The value === null check comes before the typeof value === "object" check, so in the "object" branch value is already a non-null object. typeof NaN is "number", so a number branch still needs Number.isNaN when NaN would be a problem. Arrays also report "object", so Array.isArray has to come before the generic object check if you want to tell them apart.
Narrowing with instanceof
instanceof checks whether a value was created by a given constructor, by looking for Constructor.prototype in the value's prototype chain. When the left side is unknown, TypeScript narrows it to the constructor's instance type.
function summarize(value: unknown): string {
if (value instanceof Date) {
return Number.isNaN(value.getTime()) ? "invalid date" : value.toISOString();
}
if (value instanceof Error) {
return `${value.name}: ${value.message}`;
}
if (value instanceof Map) {
return `map with ${value.size} entries`;
}
return "something else";
}
console.log(summarize(new Date(0))); // 1970-01-01T00:00:00.000Z
console.log(summarize(new TypeError("bad input"))); // TypeError: bad input
console.log(summarize(new Map([["a", 1]]))); // map with 1 entriesinstanceof has limits you should know about:
- It works only with classes and constructor functions. Interfaces and type aliases do not exist at runtime, so
value instanceof Useris an error whenUseris an interface. - It never matches primitives.
"abc" instanceof Stringisfalse, so usetypeoffor strings, numbers, and booleans. - It can fail across realms. An
Errorcreated in another iframe, a Nodevmcontext, or a duplicated copy of a library has a differentErrorconstructor, so the check returnsfalseeven though the value looks right. When this matters, check for the properties you need instead. - Narrowing to
Mapgives youMap<any, any>. The element types are not verified, so the contents areanyuntil you check them.
Narrowing with in
The in operator tests whether a property name exists on an object, including inherited properties. Before TypeScript 4.9, in could not narrow unknown at all. Since 4.9, a successful "name" in value check narrows an object to object & Record<"name", unknown>. That means you can read value.name, and its type is unknown, which you then narrow further.
function readName(value: unknown): string | undefined {
if (typeof value === "object" && value !== null && "name" in value) {
// value is object & Record<"name", unknown> here
if (typeof value.name === "string") {
return value.name;
}
}
return undefined;
}
console.log(readName({ name: "Ada" })); // Ada
console.log(readName({ name: 42 })); // undefined
console.log(readName(null)); // undefined
console.log(readName("Ada")); // undefinedThe typeof value === "object" && value !== null part is required. The right operand of in must be an object type. At runtime, "name" in null throws a TypeError, and "name" in "Ada" throws as well. The compiler rejects in on a value of type unknown for that reason.
Other checks that narrow
Several other checks also work on unknown:
- Equality:
value === "ok"narrows to the literal type"ok", andvalue === undefinednarrows toundefined. - Truthiness:
if (value)removesnull,undefined,0,"", andfalse, but the remaining type is still mostlyunknown. Truthiness rarely gives you a useful type by itself. Array.isArray(value): narrowsunknowntoany[]. Theanyleaks in here, and the next example shows how to contain it.
function sumNumbers(value: unknown): number {
if (!Array.isArray(value)) return 0;
const items: unknown[] = value; // any[] assigned to unknown[]: elements are unknown again
let total = 0;
for (const item of items) {
if (typeof item === "number") total += item;
}
return total;
}
console.log(sumNumbers([1, "two", 3, null])); // 4
console.log(sumNumbers("not an array")); // 0Assigning the any[] to a variable typed unknown[] is a safe step. It re-imposes the checking that Array.isArray dropped.
Combining checks
Real data needs several checks in sequence. The usual order is to establish the broad kind first, then rule out null, then test properties, then test each property's type. The diagram shows the decision path for an unknown value that should be an object with a string name.
Common errors
- Error:
'value' is of type 'unknown'. You usedvaluebefore any check. Add atypeof,instanceof, orincheck around the use. - Error:
'value' is possibly 'null'. You checkedtypeof value === "object"but did not excludenull. Addvalue !== null. - Error:
The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type. You used an interface or type alias. Use a class, or write a type guard. - Narrowing disappears inside a callback. TypeScript may reset narrowing for
letvariables and mutable properties inside a closure. Copy the narrowed value into aconstfirst. inworks in the editor but fails to compile. Your TypeScript version is older than 4.9. Upgrade, or fall back to a type assertion after a manual check.- Check passes but the data is wrong. Narrowing the top level does not validate nested data.
value instanceof Mapsays nothing about what the map holds.
Exercises
Exercise
The function below fails to compile. Why, and what is the smallest fix that keeps value as unknown?
function hasId(value: unknown): boolean {
return typeof value === "object" && "id" in value;
}
Show answer
After typeof value === "object", the type of value is object | null. The in operator needs a non-null object on its right side, so the compiler reports that value is possibly null. Add value !== null to the condition: typeof value === "object" && value !== null && "id" in value. The function then compiles and also avoids the runtime TypeError that "id" in null would throw.
Exercise
Write a function getMessage(value: unknown): string that returns the message of an Error, returns the value itself if it is a string, returns the message property if the value is a plain object whose message is a string, and returns "unknown error" for everything else.
Show answer
One solution:
function getMessage(value: unknown): string {
if (value instanceof Error) return value.message;
if (typeof value === "string") return value;
if (
typeof value === "object" &&
value !== null &&
"message" in value &&
typeof value.message === "string"
) {
return value.message;
}
return "unknown error";
}
The order matters little here, but the instanceof Error check comes first because it is cheap and covers the common case. The last branch uses all four steps: object kind, non-null, property exists, property type.