Interface type check with Typescript

前端 未结 17 1304
灰色年华
灰色年华 2020-11-22 14:09

This question is the direct analogon to Class type check with TypeScript

I need to find out at runtime if a variable of type any implements an interface. Here\'s my

17条回答
  •  天涯浪人
    2020-11-22 14:32

    typescript 2.0 introduce tagged union

    Typescript 2.0 features

    interface Square {
        kind: "square";
        size: number;
    }
    
    interface Rectangle {
        kind: "rectangle";
        width: number;
        height: number;
    }
    
    interface Circle {
        kind: "circle";
        radius: number;
    }
    
    type Shape = Square | Rectangle | Circle;
    
    function area(s: Shape) {
        // In the following switch statement, the type of s is narrowed in each case clause
        // according to the value of the discriminant property, thus allowing the other properties
        // of that variant to be accessed without a type assertion.
        switch (s.kind) {
            case "square": return s.size * s.size;
            case "rectangle": return s.width * s.height;
            case "circle": return Math.PI * s.radius * s.radius;
        }
    }
    

提交回复
热议问题