【问题标题】:Keep type structure of object保持对象的类型结构
【发布时间】:2018-02-11 06:53:08
【问题描述】:

我有一个函数可以将一个对象转换为另一个具有非常特定规则的对象。我想下面的函数可以作为一个例子:

interface SomethingWithAValue<T> {
  value: T;
}

function transform(obj) {
  let value = {};
  for(let key in obj) {
    value[key] = obj[key].value;
  }
  return { value };
}

这基本上转换了一个类型的对象(伪代码)

{
  [key 1]: SomethingWithAValue<type 1>,
  [key 2]: SomethingWithAValue<type 2>,
  ...
  [key n]: SomethingWithAValue<type n>
}

进入类型的新对象(再次伪代码)

SomethingWithAValue<{
  [key 1]: type 1,
  [key 2]: type 2,
  ...
  [key n]: type n
}>

我仍然需要向transform 添加正确的类型声明,那么这里最好的方法是什么?

【问题讨论】:

    标签: typescript object generics types


    【解决方案1】:

    啊,你需要mapped typesinference from mapped types

    以下是如何使用映射类型来表示从常规对象到所有属性值都包含在 SomethingWithAValue&lt;&gt; 中的对象的映射:

    type SomethingMapper<T> = {
      [K in keyof T]: SomethingWithAValue<T[K]>
    }
    
    type Example = {
      a: string,
      b: number
    }
    type SomethingMappedExample = SomethingMapper<Example>;
    // { 
    //   a: SomethingWithAValue<string>; 
    //   b: SomethingWithAValue<number>; 
    // }
    

    以下是您如何使用映射类型的推断来键入展开的函数:

    function transform<T>(obj: SomethingMapper<T>): T {
      // implementation
    }
    declare let mappedExample: SomethingMappedExample;
    const unwrapped: Example = transform(mappedExample); // okay
    

    希望对您有所帮助。祝你好运!

    【讨论】:

    • 非常感谢!这真的帮助了我!我不得不在实现中使用一些强制转换(我相信它在 TS 中称为类型断言),但它有效!
    猜你喜欢
    • 2012-02-04
    • 1970-01-01
    • 2022-08-03
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 2019-06-24
    • 1970-01-01
    相关资源
    最近更新 更多