TypeScript unknown narrowing
- Version
- es2025
- Since
- 3.0
- Review
- Draft
Summary#
Any value can be assigned to unknown, but TypeScript blocks property access and calls until a check narrows it. Use it for data whose shape has not been verified.
Syntax#
let input: unknown;
if (typeof input === "string") input.toUpperCase();
Example#
function describe(input: unknown): string {
if (typeof input === "string") return input.toUpperCase();
if (input instanceof Error) return input.message;
if (
typeof input === "object" &&
input !== null &&
"name" in input &&
typeof input.name === "string"
) {
return input.name;
}
return "unsupported";
}
const parsed: unknown = JSON.parse('{"name":"Ada"}');
console.log(describe(parsed));
console.log(describe("ready"), describe(new Error("failed")));
console.log(describe(null));
Expected output#
Ada
READY failed
unsupported
Common mistakes#
JSON.parse returns any, so annotate its result as unknown to require checks. typeof null is "object", so exclude null before using in. Finding a property does not prove its type, and an as assertion performs no runtime check.
Version applicability#
TypeScript 3.0 added unknown. TypeScript 2.7 already supported in guards for known properties. The complete example needs TypeScript 4.9 to narrow an unlisted property with in.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0