Typescript interface default values

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

    Can I tell the interface to default the properties I don't supply to null? What would let me do this

    No. But by default they are undefined which is mostly just fine. You can use the following pattern, i.e have a type assertion at the point of creation:

    let x: IX = {} as any;
    
    x.a = 'xyz'
    x.b = 123
    x.c = new AnotherType()
    

    I have this and other patterns documented here : https://basarat.gitbook.io/typescript/main-1/lazyobjectliteralinitialization

提交回复
热议问题