typescript 中的 is 关键字有什么用?
参考答案
作用
is 用于定义类型谓词(type predicate),让自定义函数具备"收窄类型"的能力。返回值写成 x is T,调用处就会把 x 收窄为 T。
function isString(x: unknown): x is string {
return typeof x === 'string';
}
function f(v: string | number) {
if (isString(v)) v.toUpperCase(); // v 收窄为 string
}
典型场景
- 联合类型分流:
type Fish = { swim: () => void };
type Bird = { fly: () => void };
const isFish = (p: Fish | Bird): p is Fish => 'swim' in p;
- 数组过滤(
filter的类型不丢):
const arr: (string | null)[] = ['a', null];
const res = arr.filter((x): x is string => x !== null); // string[]
- 外部数据校验:API 响应 /
JSON.parse的unknown校验成业务类型。 - **
asserts断言函数**(TS 3.7+):
function assertIsString(x: unknown): asserts x is string {
if (typeof x !== 'string') throw new TypeError('not string');
}
调用后整个作用域内该变量都被收窄。
注意
is只是编译期约定,函数体返回true编译器就信;写错逻辑会造成"类型撒谎",运行时出错。所以守卫内部要做真实校验。- 返回值必须是
boolean(断言函数返回void)。 - 谓词目标类型必须是参数类型的子类型,否则报错。
- 箭头函数写谓词要显式标返回类型,不能靠推导。
- 优先用内置收窄(
typeof/in/instanceof),只在无法表达时手写is。