Typescript interface default values

前端 未结 10 2048
借酒劲吻你
借酒劲吻你 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:36

    Factory method:

    You could use a factory method for this which returns an object which implements the XI interface.

    Example:

    class AnotherType {}
    
    interface IX {
        a: string,
        b: any,
        c: AnotherType | null
    }
    
    function makeIX (): IX {
        return {
        a: 'abc',
        b: null,
        c: null
        }
    }
    
    const x = makeIX();
    
    x.a = 'xyz';
    x.b = 123;
    x.c = new AnotherType();
    

    The only thing I changed with regard to your example is made the property c both AnotherType | null. Which will be necessary to not have any compiler errors (This error was also present in your example were you initialized null to property c).

提交回复
热议问题