blog

首页 / typescript / Understand That Code Generation Is Independent of Types

Understand That Code Generation Is Independent of Types

You Cannot Check TypeScript Types at Runtime

interface Square {
 width: number;
}
interface Rectangle extends Square {
 height: number;
}
type Shape = Square | Rectangle;
function calculateArea(shape: Shape) {
    if (shape instanceof Rectangle) {
    // ~~~~~~~~~ 'Rectangle' only refers to a type,
    // but is being used as a value here
    return shape.height * shape.width;
    // ~~~~~~ Property 'height' does not exist on type 'Shape'
     } else {
    return shape.width * shape.width;
    }
}

The instanceof check happens at runtime

Things to Remember