Sub topic 11
Narrowing `unknown`, Such as Parsed JSON
Assume you know basic TypeScript syntax, union types, functions, and JavaScript control flow. You should also understand that external data can be malformed, even when its documentation promises a particular shape.
Values from outside your program need a runtime check. This includes HTTP responses, configuration files, browser storage, and JSON text. TypeScript cannot inspect that data while the program runs.
Why use `unknown` at a data boundary?
unknown means “a value exists, but its type has not been established.” Unlike any, it prevents you from using the value until a check proves what it is.
function parseJson(text: string): unknown {
return JSON.parse(text) as unknown;
}
const input = parseJson('{"id": 42, "name": "Ada"}');
// Error: input is still unknown.
// console.log(input.name);JSON.parse is declared broadly in many TypeScript libraries, so wrapping it in a function that returns unknown makes the boundary explicit. The program must then validate the result before using it.
Build a type guard for the expected shape
A type guard is a function whose return type uses a type predicate. The expression value is ApiUser tells TypeScript that a true result means value has the ApiUser type.
type ApiUser = {
id: number;
name: string;
};
function isApiUser(value: unknown): value is ApiUser {
if (typeof value !== "object" || value === null) {
return false;
}
if (!("id" in value) || !("name" in value)) {
return false;
}
return (
typeof value.id === "number" &&
typeof value.name === "string"
);
}
function parseJson(text: string): unknown {
return JSON.parse(text) as unknown;
}
function showUser(text: string): string {
const value = parseJson(text);
if (!isApiUser(value)) {
return "Invalid user data";
}
return `${value.id}: ${value.name}`;
}
console.log(showUser('{"id":42,"name":"Ada"}'));
console.log(showUser('{"id":"42","name":"Ada"}'));The guard checks each property that the program will use. Checking only that the value is an object is not enough. An object can have missing properties or properties with the wrong types.
The narrowing path
A reliable guard usually follows this order:
The typeof value === "object" check excludes primitive values, but JavaScript reports null as an object. That is why the explicit value === null check is necessary.
Validate nested data
For nested objects or arrays, create smaller guards and call them from the larger guard. For example, an ApiUser with an roles: string[] property needs checks for both the array and every element. A check for Array.isArray(value.roles) alone does not prove that its elements are strings.
Use unknown when data crosses into your program. Narrow it close to that boundary, then pass validated domain values to the rest of the application.
Exercise
Why must a guard check both typeof value === "object" and value !== null before using the in operator?
Show answer
Because JavaScript treats null as an object, but the in operator cannot safely inspect null. The two checks establish a non-null object first.