This is called User-Defined Type Guards .
Regulators of the usual type allow you to do this:
function fn(obj: string | number) {
if (typeof obj === "string") {
console.log(obj.length);
} else {
console.log(obj);
}
}
So you can use typeofor instanceof, but what about these interfaces:
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)) {
} else {
}
}
( )