Typescript interface default values

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

    You can't set default values in an interface, but you can accomplish what you want to do by using Optional Properties (compare paragraph #3):

    https://www.typescriptlang.org/docs/handbook/interfaces.html

    Simply change the interface to:

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

    You can then do:

    let x: IX = {
        a: 'abc'
    }
    

    And use your init function to assign default values to x.b and x.c if those properies are not set.

提交回复
热议问题