TypeScript 7 reference · Type Operators and Keywords
TypeScript unknown Keyword
The type-safe 'anything': a value of type unknown must be narrowed (checked) before you can use it, unlike any.
TypeScript 7 Since 3.0
Examples
function parse(json: string): unknown {
return JSON.parse(json);
}
const data = parse('{"name":"Ana"}');
// @ts-expect-error: unknown must be narrowed first
data.name;
if (typeof data === "object" && data !== null && "name" in data) {
console.log(data.name);
}
Output
Ana
try {
throw new Error("boom");
} catch (err: unknown) {
console.log(err instanceof Error ? err.message : String(err));
}
Output
boom
Version history
| Version | Change |
|---|---|
| TypeScript 3.0 | Added |
Related
never· The type with no values: for functions that never return, impossible branches, and exhaustiveness checks.type predicates (x is T)· A function returning 'value is Type' tells TypeScript that the value has that type wherever the function returns true.- TypeScript keyof, typeof and Indexed Access · tutorial