Careeroza
The unknown Type
unknown is the Safe any
unknown also accepts any value, but you cannot use it until you check what it is. Use it for data you do not control: JSON.parse results, API responses, caught errors.
Example
Using an unknown value directly is an error (TS18046).
const input: unknown = JSON.parse('{"price": 100}');
console.log(input.price);Compiler output (tsc)
Line 2: error TS18046: 'input' is of type 'unknown'.
Narrow It First
Example
After a typeof or property check, TypeScript knows the exact type inside the if block. This is called narrowing.
function describe(value: unknown): string {
if (typeof value === "string") return "text of length " + value.length;
if (typeof value === "number") return "number " + value.toFixed(1);
if (Array.isArray(value)) return "array of " + value.length;
if (typeof value === "object" && value !== null && "price" in value) {
return "object with price " + String(value.price);
}
return "something else";
}
console.log(describe("hello"));
console.log(describe(3.14159));
console.log(describe([1, 2, 3]));
console.log(describe(JSON.parse('{"price": 100}')));
console.log(describe(true));Output
text of length 5 number 3.1 array of 3 object with price 100 something else