我正在尝试为我的数据库代码创建一个辅助函数。数据库中的每个表都有一些公共字段(pk、创建日期等),这些字段被实现为其他表的接口扩展的公共接口。我想创建一个函数,自动将这些公共属性添加到对象并返回新对象,但是打字稿以我无法理解的方式抱怨子类型分配......
Type '{ id: string; } & Pick<T, Exclude<keyof T, "id">>' is not assignable to type 'T'.
'{ id: string; } & Pick<T, Exclude<keyof T, "id">>' is assignable to the constraint of type
'T', but 'T' could be instantiated with a different subtype of constraint 'Common'
我在 TS 操场上做了一个最小的代码示例来重现它。对于给定类型,T 扩展了 Common 基接口,我想接受一个包含 T 的所有必需字段的对象,除了Common 中的那些,然后返回带有添加字段的对象。
interface Common {
id: string;
}
interface Table extends Common {
data: string;
}
function makeDbEntry<T extends Common>(initial: Omit<T, 'id'>): T {
const common: Common = {
id: 'random string',
};
const ret: T = {
...common,
...initial,
};
return ret;
}
据我所知,似乎没有任何方法可以在不明确列出其字段的情况下从 T 中删除字段(不能执行“T 减去 Common”)...