这看起来很容易,但我真的无法让它发挥作用。我试图将我的对象映射到另一个只有嵌套属性的对象。例子:
const child1: Child<string> = { nested: "one" };
const child2: Child<number> = { nested: 2 };
type Child<T> = { nested: T };
const abc = {
child1,
child2
}
const nestedOnly = {
child1: abc.child1.nested,
child2: abc.child2.nested
}
如何编写一个通用函数,它将任何对象作为参数并仅返回具有嵌套属性的对象而不会丢失特定类型?它的工作方式与 Array.map 类似。我试过这个:
function get<T>(ac: T){
return Object
.keys(ac)
.reduce((result, currentKey) => {
result[currentKey] = ac[currentKey].nested
return result;
}, {});
}
但它失去了打字。我还尝试在打字稿中创建映射类型并将其转换到此函数中,但我无法弄清楚这种类型应该是什么样子。
这是我想出的一种类型:
type NestedType<T extends typeof abc> = {[P in keyof T]: T[P]['nested']}
它似乎工作正常但是我需要在这里摆脱 typeof abc 因为它必须是通用函数。有没有办法说 T[P] 必须在这种类型中具有“嵌套”属性?
你很接近,我想。我会这样定义:
type NestedType<T extends { [k: string]: { nested: any } }> = {[P in keyof T]: T[P]['nested']}
因此,T
必须扩展的类型是string
其值包含nested
属性的键。
您可以验证它是否NestedType<typeof abc>
有效并且是您所期望的。祝你好运!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句