typescript - 使用与其他相同的键声明对象
问题描述
我想声明一个对象到另一个对象的映射。
第一个对象可以具有任何字符串键和泛型类型的值。
我想用相同的键映射这个对象,值的类型可以是任何东西(但如果我能从泛型中提取它们就好了)。具体来说,这些是类的属性,第一个是在构造函数中传递的。
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
}
}
解决方案
我认为这样做的方法是使C
自己成为一个泛型类,其类型参数T
对应于ob1
or的类型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
推荐阅读
- excel - 此时无法进入中断模式,同时以编程方式将代码添加到工作表
- google-apps-script - Apps 脚本 URLFetchApp 超时太早
- c# - 如何让 CSS 动画在电子邮件中工作?
- python - 在pytorch中计算困惑度
- reactjs - [未处理的承诺拒绝:TypeError:未定义不是对象(评估'Expo.Facebook.logInWithReadPermissionsAsync')]
- javascript - 在javascript中计算IST时间差
- c++ - C++如何正确使用静态变量?
- reactjs - React Js:无法重置嵌套状态
- wordpress - Wordpress 管理菜单,显示顶层的另一个名称
- eclipse - 可以将黄瓜步骤与相应的已定义步骤定义链接