Sub topic 11
Narrowing unknown, such as parsed JSON
This chapter assumes you know typeof, in, and instanceof narrowing, and that you can write a type predicate (value is T). It builds on them to handle values whose shape you do not know at compile time. The examples need TypeScript 4.9 or later, and they assume strict mode.
Why unknown exists
Data from outside your program has no type the compiler can verify. This includes HTTP responses, files, localStorage, and message payloads. TypeScript offers two top types for it, any and unknown.
| Property | `any` | `unknown` |
|---|---|---|
| Accepts any value on assignment | Yes | Yes |
| Property access without a check | Allowed | Error |
| Calling the value without a check | Allowed | Error |
| Assignable to other types | Yes | Only to `unknown` and `any` |
| Narrowable | Not usefully | Yes |
JSON.parse is declared as returning any. That return type switches off checking for everything that follows. If you annotate the result as unknown, the compiler forces you to prove the shape before you use it.
const raw: unknown = JSON.parse('{"id": 1, "name": "Ada"}');
// raw.name; // Error: 'raw' is of type 'unknown'.
// raw.toUpperCase(); // Error: 'raw' is of type 'unknown'.
if (typeof raw === "string") {
console.log(raw.toUpperCase()); // raw is string here
}A callout is worth stating early, because it affects how you write the rest of the code.
What narrowing can do with unknown
The built-in checks work on unknown, but they narrow it to different results than they do for a union.
typeof x === "string","number","boolean","bigint","symbol", and"undefined"narrow to that primitive type.typeof x === "object"narrows toobject | null. You must excludenullseparately, becausetypeof nullis"object".typeof x === "function"narrows toFunction, which you cannot call with useful types.Array.isArray(x)narrows toany[]. The elements areany, so check them before you trust them.x instanceof Datenarrows toDate.x === nullorx === undefinednarrow to those literal types."id" in xworks only afterxis known to be an object. Since TypeScript 4.9, it narrowsobjecttoobject & Record<"id", unknown>.
The last rule is what makes it possible to read properties of parsed data without a cast. The property exists, but its type is still unknown, so you check it again.
function describe(input: unknown): string {
if (typeof input === "object" && input !== null && "id" in input) {
// input is now: object & Record<"id", unknown>
return typeof input.id === "number"
? `numeric id ${input.id}`
: "id is not a number";
}
return "no id";
}
console.log(describe({ id: 7 }));
console.log(describe({ id: "7" }));
console.log(describe(null));Each level of nesting repeats this pattern: check it is an object, check it is not null, check that the key exists, then check the value's type. Written inline, this becomes unreadable quickly. A user-defined guard hides it behind one name.
Writing a guard for a data shape
A guard for a data shape returns value is ApiUser. The compiler does not verify the body. If you return true for a value that does not match, every caller gets a wrong type with no error. The guard must therefore check every field that the type promises.
type ApiUser = { id: number; name: string };
function isApiUser(value: unknown): value is ApiUser {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
"name" in value &&
typeof value.id === "number" &&
typeof value.name === "string"
);
}
function show(input: unknown): string {
return isApiUser(input) ? input.name : "not a user";
}
console.log(show({ id: 1, name: "Ada" })); // Ada
console.log(show({ id: "1", name: "Ada" })); // not a user
console.log(show(42)); // not a userThe checks run left to right, and each one narrows the value for the next. After "id" in value, the expression value.id is allowed. If you swapped the order and wrote typeof value.id first, the compiler would reject it.
A shared helper for objects
If you write many guards, the first two checks repeat. Extract them into a helper whose predicate type makes the property reads simple.
function isRecord(value: unknown): value is Record<string, unknown> {
return (
typeof value === "object" && value !== null && !Array.isArray(value)
);
}
type Account = { owner: string; tags: string[]; nickname?: string };
function isAccount(value: unknown): value is Account {
if (!isRecord(value)) return false;
if (typeof value.owner !== "string") return false;
if (
!Array.isArray(value.tags) ||
!value.tags.every((t): t is string => typeof t === "string")
) {
return false;
}
return value.nickname === undefined || typeof value.nickname === "string";
}
console.log(isAccount({ owner: "Ada", tags: ["a"] })); // true
console.log(isAccount({ owner: "Ada", tags: [1] })); // false
console.log(isAccount({ owner: "Ada", tags: [], nickname: 5 })); // falseThree details matter here.
Record<string, unknown>lets you readvalue.ownerwithout anincheck. Its type isunknown, so you still have to check it.Array.isArrayexcludes arrays, which are also objects. Without that check,[]would passisRecord.- For an optional field, accept both a missing value and a correctly typed one. Rejecting
undefinedwould make the guard stricter than the type.
Arrays of a shape
Reuse a guard for elements instead of repeating its checks. Array.prototype.every has an overload that takes a type predicate, so the result is narrowed.
type ApiUser = { id: number; name: string };
function isApiUser(value: unknown): value is ApiUser {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
"name" in value &&
typeof value.id === "number" &&
typeof value.name === "string"
);
}
function isApiUserList(value: unknown): value is ApiUser[] {
return Array.isArray(value) && value.every(isApiUser);
}
const parsed: unknown = JSON.parse('[{"id":1,"name":"Ada"},{"id":2,"name":"Lin"}]');
if (isApiUserList(parsed)) {
console.log(parsed.map((u) => u.name).join(", ")); // Ada, Lin
}A complete parse function
JSON parsing has two failure modes: the text may not be valid JSON, and valid JSON may have the wrong shape. Handle both at the boundary and give the rest of your program a typed result.
type ApiUser = { id: number; name: string };
function isApiUser(value: unknown): value is ApiUser {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
"name" in value &&
typeof value.id === "number" &&
typeof value.name === "string"
);
}
function parseUser(text: string): ApiUser | null {
let data: unknown;
try {
data = JSON.parse(text);
} catch {
return null; // not valid JSON
}
return isApiUser(data) ? data : null;
}
console.log(parseUser('{"id": 3, "name": "Grace"}')); // { id: 3, name: 'Grace' }
console.log(parseUser('{"id": "3"}')); // null
console.log(parseUser("{oops")); // nullThe data variable is declared as unknown and assigned inside try. After the try block, the compiler knows the catch path returned, so data is definitely assigned when the guard runs.
Common mistakes
- Incomplete guards. A guard that checks only
typeof value === "object"and returnsvalue is ApiUsercompiles and lies. Test each guard with a value that is missing each field in turn, and with a field of the wrong type. - Extra properties. The guards above accept
{ id: 1, name: "A", admin: true }. This is normal for structural types. If you forward the object to something that treats unknown keys as meaningful, copy out only the fields you checked. - Values that JSON cannot carry. JSON has no
Date,undefined,bigint, orNaN. A date arrives as a string, andtypeof value.createdAt === "string"is the correct check. Convert it to aDateafter the guard passes. - Numbers that are not usable.
typeof x === "number"is also true forNaNandInfinity. AddNumber.isFinite(x)if you need an ordinary number. Plain JSON text cannot produce those two values, but data built in code can. - Casting to silence the error.
value as ApiUserskips the proof thatunknownexists to demand. Use it only where you have verified the shape by other means. - Catch variables. With
strict, theerrorincatch (error)isunknown. Narrow it witherror instanceof Errorbefore readingerror.message.
Exercise
Write a type guard isPoint(value: unknown): value is { x: number; y: number }. It must return false for null, for arrays, and for objects where either coordinate is not a number. Then explain why typeof value === "object" && "x" in value && "y" in value alone is not enough.
Show answer
A correct version is: function isPoint(value: unknown): value is { x: number; y: number } { return ( typeof value === "object" && value !== null && "x" in value && "y" in value && typeof value.x === "number" && typeof value.y === "number" ); } An array cannot pass, because it has no "x" key, and null fails the explicit check. The shorter version is not enough because "x" in value narrows the property to unknown, not to number. An object such as { x: "1", y: null } would pass it, and the predicate would then tell callers that x and y are numbers. The compiler trusts the guard body, so the typeof checks on each property are what make the predicate true.
Exercise
What is the type of data inside the if block, and why is the cast-free code safe? const data: unknown = JSON.parse(text); if (typeof data === "object" && data !== null) { /* here */ }
Show answer
Inside the block, data has type object. The typeof check narrows unknown to object | null, and the !== null check removes null. Property access is still an error at this point, because object has no known properties. You must narrow further, for example with an in check or a guard such as isRecord, before reading any property.