Typescript interface default values

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

    I stumbled on this while looking for a better way than what I had arrived at. Having read the answers and trying them out I thought it was worth posting what I was doing as the other answers didn't feel as succinct for me. It was important for me to only have to write a short amount of code each time I set up a new interface. I settled on...

    Using a custom generic deepCopy function:

    deepCopy = (input: any): T => {
      return JSON.parse(JSON.stringify(input));
    };
    

    Define your interface

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

    ... and define the defaults in a separate const.

    const XDef : IX = {
        a: '',
        b: null,
        c: null,
    };
    

    Then init like this:

    let x : IX = deepCopy(XDef);
    

    That's all that's needed..

    .. however ..

    If you want to custom initialise any root element you can modify the deepCopy function to accept custom default values. The function becomes:

    deepCopyAssign = (input: any, rootOverwrites?: any): T => {
      return JSON.parse(JSON.stringify({ ...input, ...rootOverwrites }));
    };
    

    Which can then be called like this instead:

    let x : IX = deepCopyAssign(XDef, { a:'customInitValue' } );
    

    Any other preferred way of deep copy would work. If only a shallow copy is needed then Object.assign would suffice, forgoing the need for the utility deepCopy or deepCopyAssign function.

    let x : IX = object.assign({}, XDef, { a:'customInitValue' });
    

    Known Issues

    • It will not deep assign in this guise but it's not too difficult to modify deepCopyAssign to iterate and check types before assigning.
    • Functions and references will be lost by the parse/stringify process. I don't need those for my task and neither did the OP.
    • Custom init values are not hinted by the IDE or type checked when executed.

提交回复
热议问题