TypeScript自定义对象映射

时间:2020-09-28 09:15:37

标签: typescript mapping

我有一个Typescript对象,看起来像这样:

{
    "obj1" : { object: type1;};
    "obj2" : { object: type2;};
    "obj3" : { object: type3;};
    "obj4" : { object: type4;};
    "obj5" : { object: type5;};
}

我想将其映射到

{
    "obj1" : type1;
    "obj2" : type2;
    "obj3" : type3;
    "obj4" : type4;
    "obj5" : type5;
}

我担心的是在这里保留类型。

我正在使用打字稿3.7.2 即使有更高版本的解决方案,也请告诉我。

任何人都可以帮忙吗?

更新---- 我的问题是键入的不是对象映射。 我希望在编译时反映出对象的类型。

2 个答案:

答案 0 :(得分:3)

喜欢吗?

interface Foo {
  obj1: { object: string };
  obj2: { object: number };
  obj3: { object: boolean };
}

type FooMapped = { [key in keyof Foo]: Foo[key]["object"] };

const foom: FooMapped = {
  obj1: "obj1",
  obj2: 432,
  obj3: true
}

还有一个更通用的解决方案:

function mapObject<R extends Record<string, { object: unknown }>>(record: R) {
  let ret: any = {};
  Object.keys(record).forEach((key) => {
    ret[key] = record[key]["object"];
  });

  return ret as {
    [key in keyof R]: R[key]["object"];
  };
}

const foo = mapObject({
  bar: { object: 412 },
  baz: { object: true }
});

console.log(foo);

答案 1 :(得分:0)

请查看以下代码:

let objects = {
    "obj1" : { "object": "type1"},
    "obj2" : { "object": "type2"},
    "obj3" : { "object": "type3"},
    "obj4" : { "object": "type4"},
    "obj5" : { "object": "type5"},
};
for (let key of Object.keys(objects)) {
  objects[key] = objects[key]['object'];
}
console.log(objects);