我正在寻找一种为具有附加动态属性的对象创建类型的方法。
这是我尝试过的。
interface Entity {
id: string;
name: string;
}
interface NestedEntity {
id: string;
name: string;
}
const getNestedObject = () => {
return {
id: "1",
name: "test1",
}
}
const expand = <T>(obj: Entity, path: string): Entity & { [path]: T } => {
const nested = getNestedObject() as any;
return {
...obj,
[path]: nested,
}
}
const entity: Entity = {
id: "1",
name: "test1",
}
const obj = expand<NestedEntity>(entity, "nested");
obj.nested // should be visible.
我认为Entity & { [path]: T }
结果太天真了,应该以不同的方式完成。
如何解决这个问题?
干杯
只需添加重载:
interface Entity {
id: string;
name: string;
}
interface NestedEntity {
id: string;
name: string;
}
const getNestedObject = () => {
return {
id: "1",
name: "test1",
}
}
function expand<Obj, Path extends string>(obj: Obj, path: Path): Obj & Record<Path, ReturnType<typeof getNestedObject>>
function expand<Obj, Path extends string>(obj: Obj, path: Path) {
const nested = getNestedObject();
return {
...obj,
[path]: nested,
}
}
const entity: Entity = {
id: "1",
name: "test1",
}
const obj = expand(entity, "nested");
obj.nested // should be visible.
请记住,如果您使用像{ [path]:... }
TS 这样的计算属性,则不会将 is 视为Record<path, any>
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句