【问题标题】:How can preserve the types for a mapped object in Typescript如何在 Typescript 中保留映射对象的类型
【发布时间】:2018-05-06 18:49:16
【问题描述】:

如果我有一个字典对象,例如:

const x = {
  foo: {inner: 3},
  bar: {inner: 'hi'},
};

有一个不同类型的内部属性(例如这里的字符串和数字)。

然后我想将其映射到如下结构:

const y = {
  foo: 3,
  bar: 'hi',
};

但是我希望能够自动执行此操作而不会丢失任何类型信息。这在 Typescript 中是否可行?

我可以几乎用 lodash 到达那里:

import { mapValues } from 'lodash';
const y: Y = mapValues(x, (z) => z.inner);

然而,这最终会采用类型签名的字典中所有类型的联合:

const y: {
    foo: string | number;
    bar: string | number;
}

而不是想要的:

const y: {
  foo: number;
  bar: string;
};

【问题讨论】:

  • 你写了const y = { inner: 3, inner: 'hi', };;真的是你的意思吗?
  • 哎呀,你是对的,应该是:const y = { foo: 3, bar: 'hi', };

标签: typescript


【解决方案1】:

这样的事情应该可以工作:

type Wrapped<T> = {[K in keyof T]: {inner: T[K]}};

function unwrap<T>(x: Wrapped<T>): T {
  // (the implementation here is not the point)
  return _.mapValues(x as any, z => z.inner) as T;
}

const y = unwrap(x);

参考:https://www.typescriptlang.org/docs/handbook/advanced-types.html(最后一段)

【讨论】:

  • 我仍在试图弄清楚这是如何工作的,但它确实有效!你是闪亮的神!
  • 这似乎在没有as any 和没有as T 的情况下也可以工作。
猜你喜欢
  • 2018-04-04
  • 1970-01-01
  • 2021-03-28
  • 1970-01-01
  • 2020-11-25
  • 1970-01-01
  • 2020-05-03
  • 2018-10-08
  • 2020-03-30
相关资源
最近更新 更多