最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is the benefit of using "is" keyword in TypeScript? - Stack Overflow

programmeradmin1浏览0评论

What is the difference below? I sometimes see is keyword in typescript but could not figure out the benefit using arg is string in this case. Looked up but not much information about it. Could someone explain?

const isString = (arg: any): arg is string  => typeof arg === "string";  

const isString = (arg: any) => typeof arg === "string";

What is the difference below? I sometimes see is keyword in typescript but could not figure out the benefit using arg is string in this case. Looked up but not much information about it. Could someone explain?

const isString = (arg: any): arg is string  => typeof arg === "string";  

const isString = (arg: any) => typeof arg === "string";
Share Improve this question asked Sep 12, 2019 at 10:04 shinyatkshinyatk 1,0653 gold badges17 silver badges34 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

That's a user-defined type guard. It means that when calling isString TypeScript knows to narrow down the type to string if it returns true.

An example:

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

If the function doesn't define a custom type guard, the type inside the if block would still be string | number and calling toLowerCase() would produce an error.

With the type guard, the piler narrows down the type to string inside the if block.

Playground

发布评论

评论列表(0)

  1. 暂无评论