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
1 Answer
Reset to default 11That'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