TypeScript Unknown
The unknown type is a type for a value whose kind is not yet known. It accepts every value, and it blocks every use until a check narrows it.
Unknown accepts every value
Assignment never fails for an unknown variable. The typeof logs show the kind stored at each step.
let data: unknown = "hello";
console.log(typeof data);
data = 42;
console.log(typeof data);Direct use is refused
The value holds a string, and the call still fails. The compiler cannot prove the kind before a check runs.
let data: unknown = "hello";
console.log(data.toUpperCase());A typeof check unlocks the value
The typeof check tests the kind stored in the value. Inside the string branch, string methods are allowed.
let data: unknown = "hello";
if (typeof data === "string") {
console.log(data.toUpperCase());
}Example
function describe(data: unknown) {
if (typeof data === "string") {
console.log("Text:", data);
} else if (typeof data === "number") {
console.log("Number:", data);
} else if (typeof data === "boolean") {
console.log("Flag:", data);
} else {
console.log("Other kind");
}
}
describe("hello");
describe(42);
describe(true);
describe(null);Key points
- Unknown accepts a value of every type.
- An unknown value cannot be used until a check narrows it.
- A typeof check narrows an unknown value inside its branch.
- Reading a property of an unknown value raises a type error.
In this example, describe takes one unknown value. Each typeof branch handles one kind and logs its own line. The null call matches no branch, so the last line logs Other kind.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
What must happen before an unknown value can be used as a string?