代码之家  ›  专栏  ›  技术社区  ›  Milad

如何优雅地重写对象,同时严格检查其嵌套属性

  •  0
  • Milad  · 技术社区  · 8 年前

    如果有的话

    interface Human{
      name:string
      age:number
      dimensions : {
        height:number
        width:number
      }
    }
    
    const base : Human ={
      name:"Base",
      age:12,
      dimensions : {
        height:190,
        width:99
      }
    };
    
    
    const child : Human = lodashMerge(base,{
      age:22,
      dimentions:{
         height:99
      }
    }) // this should work , shouldn't throw 
    
    
    const child2 : Human = lodashMerge(base,{
      hairColor:'red'
    }) // should throw because hairColor does not exist in base 
    
    2 回复  |  直到 8 年前
        1
  •  2
  •   CRice    8 年前

    假设 lodashMerge 是罗达什的 _.merge 方法,您将无法执行此操作并继续单独使用该方法。您必须将它包装到自己的函数中,这样就可以添加更严格的类型定义,因为lodash本身给出的定义过于宽松。

    The type definition for that method can be found here ,如您所见,每个重载的返回类型只是其参数的交集类型,在这里,您可能希望返回类型正好是第一个参数的类型。

    所以我建议用您想要的签名将该方法包装到您自己的函数中。可能是这样的:

    // Using only the final overload (the variadic one), since thats how we call it later.
    declare function lodashMerge(object: any, ...otherArgs: any[]): any;
    
    type DeepPartial<T> = {
        [K in keyof T]?: DeepPartial<T[K]>;
    }
    
    function myMerge<T>(base: T, ...args: DeepPartial<T>[]): T {
        return lodashMerge(base, ...args);
    };
    

    然后,使用它,您将在第二个示例中得到一个错误,但在第一个示例中不会。 尽管事实上,两个维度都有错误,因为您拼错了“dimensions”。 ;)

    // No problem, works as expected.
    const child : Human = myMerge(base,{
      age:22,
      dimensions:{ // Note the change in spelling, otherwise: error.
         height:99
      }
    })
    
    // Error: See below
    const child2 : Human = myMerge(base,{
      hairColor:'red' // Error: Object literal may only specify known properties, and 'hairColor' does not exist in type 'DeepPartial<Human>'.
    })
    
        2
  •  0
  •   kctang    8 年前

    您的示例代码遗漏了决定是否检测到错误的位。这取决于如何 lodashMerge 已定义。

    如果要传递部分对象,请考虑 Partial<Human> 作为参数类型 洛达什梅 功能。否则,你可以 { age: 99 } as any 绕过类型检查。

    推荐文章