返回搜索
TypeScript Type Narrowing Issue
64次浏览11/18/2025
type-guardstype-narrowingtype-predicatestypescript

问题描述

TypeScript not properly narrowing types in conditional statements

根本原因

Type guards need to be explicit for complex types

解决方案

Use explicit type guards or type predicates to help TypeScript understand the type narrowing

背景信息

// Example of type predicate\ninterface Cat { meow(): void; }\ninterface Dog { bark(): void; }\n\nfunction isCat(animal: Cat | Dog): animal is Cat {\n return (animal as Cat).meow !== undefined;\n}\n\nfunction handleAnimal(animal: Cat | Dog) {\n if (isCat(animal)) {\n animal.meow(); // TypeScript knows this is a Cat\n } else {\n animal.bark(); // TypeScript knows this is a Dog\n }\n}