A value from outside your checked program may not match your expectations. TypeScript's unknown type makes that uncertainty explicit. You can store any value in unknown, but cannot read arbitrary properties or call it until you narrow it.
Compare unknown with any. Any allows unchecked operations to continue; unknown asks for evidence. At a boundary, unknown is usually the honest starting point. Inside trusted application logic, use a specific domain type after validation.
Start with ordinary JavaScript guards: typeof for primitive values, a null check for objects, and Array.isArray when you need to distinguish lists. Remember that typeof null is "object". Check null explicitly before treating a value as a record.
A type predicate such as value is Session describes the result of a guard function. When the function returns true, the checker trusts that claim. It does not prove your guard inspected every necessary field. A mistaken predicate can create false confidence, so keep guards small, check every promised property, and test malformed examples.
A boolean return alone can be useful, but an explicit predicate communicates narrowing to callers. Today you will first recognize a primitive, then validate whole records and domain rules. Do not use as Session to skip this work: an assertion changes what the checker believes, not the data.
Predict, check, then run
Before running, write down the output and explain which information the checker knows. Click Check types first, then Check & run.
function isText(value: unknown): value is string {
return typeof value === "string";
}
function display(value: unknown): string {
if (isText(value)) {
// The guard established that value is a string in this branch.
return value.trim();
}
return "Not text";
}
console.log(display(" Types "));
console.log(display(25));Enable JavaScript to edit and type-check this example.
Check your prediction
Types
Not textRead a real compiler error
The initializer looks familiar, but the declared boundary type intentionally withholds that promise.
const value: unknown = { topic: "Types" };
console.log(value.topic);Enable JavaScript to edit and type-check this example.
Check your diagnosis
Narrow to a non-null object and verify the topic property before reading it as text. Or, for a genuinely trusted local literal, let the checker infer its actual shape. Do not assert untrusted values into the shape you wish they had.
Check that a property exists with in
After typeof value === "object" && value !== null, the checker knows only that value is some object: type object, which has no named properties. Reading value.topic there is still an error, TS2339: Property 'topic' does not exist on type 'object'. You need one more piece of evidence.
JavaScript's in operator supplies it. "topic" in value is true when the object has a property called topic (Day 2 used it to tell an omitted note from a present one). TypeScript narrows on it too: inside the branch, value is known to have a topic property, whose type is unknown until you check it with typeof.
const value: unknown = JSON.parse('{"topic":"Types"}');
if (typeof value === "object" && value !== null && "topic" in value) {
console.log(typeof value.topic);
console.log(value.topic);
}Enable JavaScript to edit and type-check this example.
Check your prediction
string
TypesThe order matters: typeof object first (in only works on objects), then null (because typeof null is "object"), then in, then typeof on the property itself.
A guard is trusted evidence and needs honest checks
Unknown prevents using a value until evidence narrows it. A type predicate tells the checker that a successful call establishes a particular shape. The checker trusts that promise; it does not prove that the guard's body inspected every required property.
Keep predicates small and test both accepted and rejected values. A guard that merely checks typeof object still accepts null or unrelated records, depending on its exact condition. Use ordinary runtime checks to justify the stronger type you claim.
function isText(value: unknown): value is string {
return typeof value === "string";
}
const inputs: unknown[] = ["Types", 25, null];
for (const value of inputs) {
console.log(isText(value) ? value.toUpperCase() : "Not text");
}Enable JavaScript to edit and type-check this example.
Check your prediction
TYPES
Not text
Not textThe predicate narrows each individual value in the true branch. A type assertion would let the call compile without establishing the same runtime fact.
function isNonblank(value: unknown): value is string {
return typeof value === "string" && value.trim() !== "";
}
console.log(isNonblank(" "));
console.log(isNonblank(" Types "));
console.log(isNonblank(25));Enable JavaScript to edit and type-check this example.
Check your prediction
false
true
falseThis guard returns false for " ", which is a string. That is a problem, because the checker reads a predicate both ways: true means "value is a string", and false means "value is not a string". Here the input is unknown, so false only leaves it unknown and nothing breaks. Reuse the same guard on a string | number parameter and the else branch is narrowed to number:
function isNonblank(value: unknown): value is string {
return typeof value === "string" && value.trim() !== "";
}
function show(value: string | number): string {
if (isNonblank(value)) {
return value.trim();
}
return value.toFixed(1);
}
console.log(show(2));
console.log(show(" Types "));Enable JavaScript to edit and type-check this example.
Check your prediction
2.0
TypesAdd console.log(show(" ")); and run it. It passes Check types and then throws TypeError: value.toFixed is not a function, because the blank string went down the branch the checker believed was number. The rule: a value is X predicate should mean exactly "value is an X". Check the type with the predicate (or typeof), and check domain rules such as "not blank" with an ordinary boolean condition after narrowing, or in a decoder that returns a result.
Try the rule on new inputs
Test blank strings, null, arrays and records. Deliberately weaken a guard and identify which negative fixture exposes it. Explain why returning true from a predicate can be more dangerous than a normal boolean if its claim is wrong.
Debug a plausible mistake
Repair evidence before property access
Return a trimmed title only from an object containing a string title; otherwise return Invalid. Print Read then Invalid for the calls below. Include null in a later rejection check.
Use Check types to inspect the genuine diagnostic before repairing the code. Keep the intended contract; do not bypass the checker with any, a broad assertion or an ignore comment.
function label(value: unknown): string {
return value.title.trim();
}
console.log(label({ title: " Read " }));
console.log(label(25));Enable JavaScript to edit and type-check this example.
Hint 1: the idea
Unknown data has no trusted properties until runtime checks establish them.
Hint 2: a first step
Reject non-objects and null, use "title" in value to establish the property, then check its typeof before calling trim.
Show one solution
function label(value: unknown): string {
if (value === null || typeof value !== "object" || !("title" in value)) {
return "Invalid";
}
if (typeof value.title !== "string") {
return "Invalid";
}
return value.title.trim();
}
console.log(label({ title: " Read " }));
console.log(label(25));Read
InvalidEach condition supplies one fact the checker needs: typeof object and the null check make value an object, "title" in value gives it a title property of type unknown, and the typeof string check narrows that property so trim is allowed. Drop the in test and you get TS2339 on value.title. At runtime the same checks are what stop label(25) and label(null) from throwing.
Your turn
unknown & Type Guards: practice
Write isNonNegativeNumber(value: unknown): value is number. Require typeof number, Number.isFinite and value >= 0. Use it to print valid for 0 and invalid for "25", -1 and NaN.
// Guard unknown before numeric operations; test four cases.Enable JavaScript to edit and type-check this example.
Hint 1: the idea
The primitive check enables safe numeric checks; neither alone proves the domain rule.
Hint 2: a first step
Use a conjunction whose first part checks typeof value === "number".
Show one solution
function isNonNegativeNumber(value: unknown): value is number {
return typeof value === "number" && Number.isFinite(value) && value >= 0;
}
for (const value of [0, "25", -1, NaN]) {
console.log(isNonNegativeNumber(value) ? "valid" : "invalid");
}Enable JavaScript to edit and type-check this example.
valid
invalid
invalid
invalidtypeof value === "number" narrows value, which is what lets Number.isFinite(value) and value >= 0 be written at all. NaN is typeof "number", so the finiteness check is the one that rejects it. This predicate claims value is number but also rejects -1: that is safe here only because the input is unknown and a false result just prints "invalid". On a number | string input, a false for -1 would wrongly narrow it to string, as the show example above showed.
Change it and explain it
Test Infinity, null, false and 2.5. Explain why a guard that only checks typeof number would accept NaN. Then deliberately make the predicate always return true: the checker trusts it, but your tests should show why that implementation is dishonest.
Completion is saved in this browser only. It does not measure mastery.