首页 > 解决方案 > 使用与其他相同的键声明对象

问题描述

我想声明一个对象到另一个对象的映射。

第一个对象可以具有任何字符串键和泛型类型的值。

我想用相同的键映射这个对象,值的类型可以是任何东西(但如果我能从泛型中提取它们就好了)。具体来说,这些是类的属性,第一个是在构造函数中传递的。

class C {
  ob1: {
    [key: string]: Wrapper<any>
  };
  ob2; // should have the same keys as ob1

  constructor(o?: { [key: string]: Wrapper<any> }) {
    this.ob1 = o;
    // map ob2 from o
  }
}

标签: typescripttypescript-typings

解决方案


我认为这样做的方法是使C自己成为一个泛型类,其类型参数T对应于ob1or的类型ob2,然后使用映射类型来表示“相同的键但不同/相关的值”。例如:

type MappedWrapper<T> = { [K in keyof T]: Wrapper<T[K]> }
class C<T> {
  ob1: MappedWrapper<T>
  ob2: T;
  constructor(o: MappedWrapper<T>) { // made param required here
    this.ob1 = o;
    this.ob2 = mapUnwrap(o); // some function that unwraps properties
  }
}

这里我们说那T是的类型ob2,而ob1有类型MappedWrapper<T>,一个映射类型,其中的每个属性ob1都映射到一个Wrapper版本。


取决于Wrapper和相关类型的实现和声明,例如:

type Wrapper<T> = { x: T };
function wrap<T>(x: T): Wrapper<T> {
  return { x };
}
function unwrap<T>(x: Wrapper<T>): T {
  return x.x;
}
function mapUnwrap<T>(x: MappedWrapper<T>): T {
  return Object.fromEntries(Object.entries(x).map(([k, v]) => [k, unwrap(v)])) as any as T;
}

您可以验证这是否按预期工作:

const c = new C({ a: wrap(123), b: wrap("hello"), c: wrap(true) });
/* const c: C<{ a: number; b: string; c: boolean;}> */

c.ob1.a.x.toFixed(); // no error
c.ob2.b.toUpperCase(); // no error

Playground 代码链接


推荐阅读