In VSCode's source file, there are some functions with a particular return type specification, like this:
export function isString(str: any): str is string {
if (typeof (str) === _typeof.string || str instanceof String) {
return true;
}
return false;
}
So I wonder what is the purpose of "str is string" instead of just writing "boolean".
Can we use "str is string" and the like in any other circumstances?
To define the return type for the function, we have to use the ':' symbol just after the parameter of the function and before the body of the function in TypeScript. The function body's return value should match with the function return type; otherwise, we will have a compile-time error in our code.
In typescript the type keyword defines an alias to a type. We can also use the type keyword to define user defined types.
Types of Functions in TypeScript: There are two types of functions in TypeScript: Named Function. Anonymous Function.
That is called User-Defined Type Guards.
Regular type guards let you do this:
function fn(obj: string | number) {
if (typeof obj === "string") {
console.log(obj.length); // obj is string here
} else {
console.log(obj); // obj is number here
}
}
So you can use typeof
or instanceof
, but what about interfaces like this:
interface Point2D {
x: number;
y: number;
}
interface Point3D extends Point2D {
z: number;
}
function isPoint2D(obj: any): obj is Point2D {
return obj && typeof obj.x === "number" && typeof obj.y === "number";
}
function isPoint3D(obj: any): obj is Point2D {
return isPoint2D(obj) && typeof (obj as any).z === "number";
}
function fn(point: Point2D | Point3D) {
if (isPoint2D(point)) {
// point is Point2D
} else {
// point is Point3D
}
}
(code in 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