Typescript interface default values

前端 未结 10 2061
借酒劲吻你
借酒劲吻你 2020-12-02 14:44

I have the following interface in TypeScript:

interface IX {
    a: string,
    b: any,
    c: AnotherType
}

I declare a variable of that t

10条回答
  •  长情又很酷
    2020-12-02 15:31

    You can implement the interface with a class, then you can deal with initializing the members in the constructor:

    class IXClass implements IX {
        a: string;
        b: any;
        c: AnotherType;
    
        constructor(obj: IX);
        constructor(a: string, b: any, c: AnotherType);
        constructor() {
            if (arguments.length == 1) {
                this.a = arguments[0].a;
                this.b = arguments[0].b;
                this.c = arguments[0].c;
            } else {
                this.a = arguments[0];
                this.b = arguments[1];
                this.c = arguments[2];
            }
        }
    }
    

    Another approach is to use a factory function:

    function ixFactory(a: string, b: any, c: AnotherType): IX {
        return {
            a: a,
            b: b,
            c: c
        }
    }
    

    Then you can simply:

    var ix: IX = null;
    ...
    
    ix = new IXClass(...);
    // or
    ix = ixFactory(...);
    

提交回复
热议问题