2个问题:
1:为什么 ts 抱怨${R[K]}
(不可分配给类型 string | ....)以及如何修复它
2:如何在没有显式类型重影的情况下做到同样的事情?recordWithRoot as ...
const getRecordWithRoot = <T extends string, R extends {}>(
root: T,
record: R
) => {
const recordWithRoot = {
ROOT: root,
};
for (const key in record) {
Object.defineProperty(recordWithRoot, key, {
get: () => {
return root + record[key];
},
});
}
return recordWithRoot as { [K in keyof R]: `${T}${R[K]}` } & { ROOT: T };
};
const some = getRecordWithRoot(`core/A` as const, {
get A() {
return `/a` as const;
},
get B() {
return `/b` as const;
},
});
// result
// ROOT => core/A
// A => core/A/a
// B core/A/b