Predict Type Guard Output
Predict Output Medium
Question
What does this code print?
Code
function isString(x: unknown): x is string {
return typeof x === "string";
}
const val: unknown = "test";
if (isString(val)) {
console.log(val.length);
} else {
console.log("not a string");
}
Hint
val is "test", which is a string with 4 characters.
Explanation
The type guard isString(val) returns true because val is "test". Inside the if branch, TypeScript narrows val to string, so val.length is valid. "test".length is 4. The output is 4.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.