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";
                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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With