in, instanceof, discriminated unions
Use in/property checks, instanceof for classes, and discriminated unions to branch safely.
Intro
Goal: Practice three powerful guards: in for property checks, instanceof for classes, and discriminated unions for clean branching.
in operator
in narrows by testing a property name at runtime. Great for object-literal unions.
type HasLength = { length: number };
function print(v: string | HasLength) {
if ("length" in v) {
// v is HasLength
console.log("len:", v.length);
} else {
// v is string
console.log(v.toUpperCase());
}
}
print({ length: 3 });
print("ts");All lessons in this course
- typeof, equality, truthiness narrowing
- in, instanceof, discriminated unions
- Exhaustiveness with never (intro)