TypeScript-面试-类型守卫与断言
2026年10月16日·Admin·1 次浏览
面试题:类型守卫是什么?as 与 ! 的风险?
类型守卫(Type Predicate)
返回 x is SomeType 的函数,帮助编译器收窄:
function isStr(x: unknown): x is string {
return typeof x === "string"
}
内置:typeof、instanceof、in、Array.isArray。
类型断言 as
告诉编译器「相信我」,不做运行时检查。错误断言会导致运行时崩溃。仅在有逻辑保证或刚做完校验后使用。
非空断言 !
maybe!.prop 断言不是 null/undefined。滥用掩盖空值 bug;更推荐 可选链 ?. 与显式判空。
as const
字面量收窄为只读字面量联合,常用于 Redux action type、配置常量。