Typescript interface optional properties depending on other property

前端 未结 3 1948
梦如初夏
梦如初夏 2020-12-30 02:22

Let\'s say we have the following Typescript interface:

interface Sample {
    key1: boolean;
    key2?: string;
    key3?: number;
};
         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-30 03:08

    I think that a readable solution is to use overload

    so we can do this:

    type IOverload = {
      (param: { arg1: number }): any;
      (param: { arg1: number; arg2: string; arg3: number }): any;
    };
    
    const sample: IOverload = (args) => {...};
    
    sample({ arg1: 1, arg2: 'a' });
    
    ===> Property 'arg3' is missing in type '{ arg1: number; arg2: string; }' but required 
    in type '{ arg1: number; arg2: string; arg3: number; }'.
    

提交回复
热议问题