Narrowing means checking a value so TypeScript knows its exact type in a branch:
typeof x === "string"x instanceof Date"swim" in animal- Discriminated unions: a shared
kindproperty tells the variants apart.
Help TypeScript understand which type you have.
✍️ 3 exercises + code challenge in this lessonNarrowing means checking a value so TypeScript knows its exact type in a branch:
typeof x === "string"x instanceof Date"swim" in animalkind property tells the variants apart.Mastering TypeScript Narrowing & Type Guards helps you write clean and reliable TypeScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Shape = Circle | Square;
function area(s: Shape): number {
switch (s.kind) {
case "circle":
return Math.round(Math.PI * s.radius ** 2);
case "square":
return s.side ** 2;
}
}
console.log(area({ kind: "circle", radius: 2 }), area({ kind: "square", side: 3 }));
13 9
Check what you learned in “TypeScript Narrowing & Type Guards”.
Check whether value is a Date.
if (value Date) { }
What is a discriminated union?
Write len(x: string | string[]) that returns x.length for both. Log len("abc") and len(["a", "b"]) separated by a space.
Free sign-in required · Google login available
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services