Typescript interface default values

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

    You could use two separate configs. One as the input with optional properties (that will have default values), and another with only the required properties. This can be made convenient with & and Required:

    interface DefaultedFuncConfig {
      b?: boolean;
    }
    
    interface MandatoryFuncConfig {
      a: boolean;
    }
    
    export type FuncConfig = MandatoryFuncConfig & DefaultedFuncConfig;
     
    export const func = (config: FuncConfig): Required => ({
      b: true,
      ...config
    });
    
    // will compile
    func({ a: true });
    func({ a: true, b: true });
    
    // will error
    func({ b: true });
    func({});
    

提交回复
热议问题