Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the benefit of using "is" keyword in TypeScript?

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";
like image 475
shinyatk Avatar asked Oct 31 '25 07:10

shinyatk


1 Answers

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 compiler narrows down the type to string inside the if block.

Playground

like image 148
lukasgeiter Avatar answered Nov 02 '25 21:11

lukasgeiter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!