Typescript interface optional properties depending on other property

前端 未结 3 1938
梦如初夏
梦如初夏 2020-12-30 02:22

Let\'s say we have the following Typescript interface:

interface Sample {
    key1: boolean;
    key2?: string;
    key3?: number;
};
         


        
3条回答
  •  北海茫月
    2020-12-30 02:55

    Thought I'd mention another nice approach here could be to use a discriminated union:

    enum ShapeKind {
        Circle,
        Square,
    }
    
    interface Circle {
        kind: ShapeKind.Circle;
        radius: number;
    }
    
    interface Square {
        kind: ShapeKind.Square;
        sideLength: number;
    }
    
    let c: Circle = {
        kind: ShapeKind.Square,
        //    ~~~~~~~~~~~~~~~~ Error!
        radius: 100,
    }
    

    As described in the Typescript docs: https://www.typescriptlang.org/docs/handbook/enums.html#union-enums-and-enum-member-types

提交回复
热议问题