【发布时间】:2021-04-09 06:48:24
【问题描述】:
我有一个基本接口,用于处理可能有 Id 的事物:
interface Identifiable {
id?: number;
}
我有一个通用函数,可以将记录对象转换为具有 id 的事物:
function fromRowToObj1<T extends Identifiable>(row: { id: number; }): Partial<T> {
return { id: row.id };
// Type '{ id: number; }' is not assignable to type 'Partial<T>'.
}
我知道发生这种情况是因为有 Ts 扩展了 Identifiable,这会使 return 语句非法。例如,{ id: undefined } 或 { id: 1 } 类型。所以我决定稍微调整返回类型以强制使用数字 id:
type Identified<T extends Identifiable> = {
[K in keyof T]?: K extends "id" ? number : T[K];
}
// Should give something like type C = { id?: number | undefined; ... }
function fromRowToObj2<T extends Identifiable>(row: { id: number; }): Identified<T> {
return { id: row.id };
// Type '{ id: number; }' is not assignable to type 'Identified<T>'.
}
为什么?哪个可能的T(例如T extends Identifiable)使得{ id: number } 不能分配给Identified<T>?
如果无法调整Identified 类型以使其工作,是否有另一种方法可以键入转换函数以使用Identifiable 的泛型子类型?
【问题讨论】:
标签: typescript