在TypeScript中使用"is"关键字有什么好处?

4
下面有什么区别?我有时在Typescript中看到is关键字,但无法弄清楚在这种情况下使用arg is string的好处。查阅了资料,但并没有太多信息。有人能解释一下吗?
const isString = (arg: any): arg is string  => typeof arg === "string";  

const isString = (arg: any) => typeof arg === "string";
1个回答

11

这是一个用户定义的类型保护。这意味着在调用isString时,TypeScript知道如果它返回true,则能缩小类型范围至string

一个例子:

declare const foo: string | number;
if (isString(foo)) {
    console.log(foo.toLowerCase());
}

如果函数没有定义自定义类型保护,if块内的类型仍然是string | number,调用toLowerCase()会产生错误。
有了类型保护,编译器将在if块内缩小类型为stringPlayground

我知道这个问题有时候已经被回答过了,但是非常感谢你。我一直在尝试弄清楚自定义类型守卫相比于简单函数的优势,但是你的例子帮了我很多。 - tmp dev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接