typeof, instanceof, and in narrowing
What the type checker does with typeof, instanceof, and in checks, and where each one narrows less than you might expect.
Control flow analysis and narrowingUnion and literal typesany, unknown, never, and void
typeof, instanceof, and in narrowing
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Equality checks only work when the union's members are distinct values; when they are distinct kinds of thing (a string or a number, a `Date` or an `Error`, one object shape or another), you need a check that asks what kind of thing the value is.
- `typeof x === "string"` narrows to `string`, and TypeScript understands every string `typeof` can return, including `"function"`, which narrows to the callable members of a union.
- `typeof x === "object"` keeps `null` in the narrowed type, because `typeof null` is `"object"` at runtime, so an object check on a nullable value needs a separate `null` check.
- `x instanceof C` narrows to the instance type of class `C`, which is the standard way to get from `unknown` in a `catch` block to a usable `Error`.
- `"key" in x` narrows a union of object types to the members that declare `key`; members where `key` is optional stay in both branches.
- On a value already narrowed to `object`, `"key" in x` adds the property to its type as `unknown`, which is enough to start checking data whose shape you don't know.
When equality isn’t enough
The previous lesson narrowed unions by comparing against specific values: === null, === "draft". That works because those union members are specific values. It falls apart for string | number. There’s no single value to compare against, because the two members are different kinds of thing.
JavaScript already has three operators that ask “what kind of thing is this?”: typeof, instanceof, and in. How they behave at runtime belongs to the JavaScript roadmap. This lesson is about what the type checker does with each of them, which TypeScript calls type guards: runtime checks it understands well enough to narrow on.
typeof: primitives and functions
function pad(value: string | number) {
if (typeof value === "string") {
return value.padStart(5); // value: string
}
return value.toFixed(2); // value: number
}
TypeScript knows the full list of strings typeof can produce: "string", "number", "bigint", "boolean", "symbol", "undefined", "object", and "function". Compare against one of those and the checker narrows to the matching members. Compare against a typo like "strng" and it reports an error, because that comparison can never be true.
"function" is handy for APIs that take either a value or a function producing one:
function resolve(v: string | (() => string)) {
return typeof v === "function" ? v() : v; // v: () => string, then v: string
}
The typeof null hole
One runtime quirk leaks straight into the types. typeof null is "object", a bug from JavaScript’s first version that can never be fixed. TypeScript models it faithfully, so an "object" check does not remove null:
function count(tags: string[] | null) {
if (typeof tags === "object") {
return tags.length;
// error: 'tags' is possibly 'null'.
}
}
Add tags !== null to the condition, or use Array.isArray(tags), which TypeScript also recognises as a guard. The error is the checker doing its job: it caught a runtime bug you might not have.
instanceof: class instances
For values built by a class, x instanceof C narrows x to C’s instance type. The place you’ll use it most is error handling. Under strict, a caught value is unknown, since JavaScript lets you throw anything at all:
function message(e: unknown): string {
if (e instanceof Error) {
return e.message; // e: Error
}
return String(e);
}
It also works for Date, Map, DOM classes like HTMLInputElement, and your own classes. What it can’t do is recognise a shape. instanceof checks an object’s prototype chain, so a plain object from JSON.parse fails the check even if it has every property the class declares. TypeScript narrows on what the runtime check proves, nothing more.
in: object shapes
Most TypeScript data isn’t class instances. It’s plain objects described by types, and for those, "key" in x is the guard:
type Fish = { swim(): void };
type Bird = { fly(): void };
function move(animal: Fish | Bird) {
if ("swim" in animal) {
animal.swim(); // animal: Fish
} else {
animal.fly(); // animal: Bird
}
}
The checker keeps the union members that declare the key in the true branch and the rest in the false branch. A member where the key is optional goes into both, because the property might be absent.
Since TypeScript 4.9, in also works on objects whose shape you don’t know. Once a value is narrowed to object, an in check adds the property to its type as unknown:
function readId(v: unknown) {
if (typeof v === "object" && v !== null && "id" in v) {
return v.id; // v: object & Record<"id", unknown>
}
}
That unknown is the honest answer. You’ve proved the property exists, not what’s in it. Checking its type is a further guard, and when a chain like this gets long, it’s time for the custom type guards later in this group.
About the video
This is the same Nicos Tsourektsidis video as the previous lesson, starting at its “typeof Operator” chapter (7:41), followed by “instanceof Operator” at 9:45. The in operator gets its own short chapter much later, at 25:35, so skip ahead once you’ve watched the first two. The chapters in between cover truthiness, equality, and exhaustiveness, which the surrounding lessons already handle.
Check yourself
Why can't you narrow `string | number` with an `===` check the way you narrow `"draft" | "published"`?
Equality compares against one specific value, and `string` and `number` each contain infinitely many values. You need a check that tests the kind of value, which is what `typeof` does: `typeof x === "string"` covers every possible string at once.
You write `if (typeof tags === "object") { tags.length }` where `tags: string[] | null`. Why does TypeScript report that `tags` is possibly `null`?
At runtime `typeof null` returns `"object"`, so the check is true for `null` too, and TypeScript narrows to `string[] | null`. Add `tags !== null` to the condition, or test with `Array.isArray(tags)` instead.
In a `catch (e)` block under `strict`, `e` is `unknown`. How do you read `e.message` safely?
Narrow it first with `if (e instanceof Error)`. Inside that branch `e` has type `Error`, so `e.message` is allowed. Outside it, handle the case where something other than an `Error` was thrown, for example with `String(e)`.
Given `type Fish = { swim(): void }` and `type Bird = { fly(): void }`, what does `if ("swim" in animal)` do for `animal: Fish | Bird`?
In the true branch `animal` is narrowed to `Fish`, because only `Fish` declares `swim`. In the else branch it is narrowed to `Bird`. If `Bird` had an optional `swim?` property, it would appear in both branches, since an optional property might or might not be present.
Why does `instanceof` not help with a plain object parsed from JSON, even if its shape matches a class?
`instanceof` checks the prototype chain at runtime, and an object from `JSON.parse` is a plain object whose prototype is `Object.prototype`, never the class's. TypeScript narrows on what the runtime check proves, so it narrows nothing useful here; use `in` or property checks instead.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.