我有以下代码:
const translateConvertedIdentifiers = <T extends BaseQueryResponseRow>(rows: T[]): T[] => {
return rows.map((row) => {
const convertedRow = Object.entries(row).reduce<T>((acc, [key, val]) => {
return { ...acc, [key]: val };
}, {});
return convertedRow;
});
};
它扩展的类型如下:
export type BaseQueryResponseRow = { [column: string]: any };
我收到一个类型错误,表明我无法使用
{}
Argument of type '{}' is not assignable to parameter of type 'T'.
'{}' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'BaseQueryResponseRow'
但是,即使是 BaseQueryResponseRow 类型的空对象,为什么不允许呢? 当我使用
as T
时它可以工作,但我将其视为此功能的最后手段。
我应该怎样做才能正确解决这个问题?
您可以对累加器使用类型断言,在这种情况下它是有效的:
type BaseQueryResponseRow = { [column: string]: any };
const translateConvertedIdentifiers = <T extends BaseQueryResponseRow>(rows: T[]): T[] => {
return rows.map((row) => {
const convertedRow = Object.entries(row).reduce((acc, [key, val]) => {
return { ...acc, [key]: val };
}, {} as T);
return convertedRow;
});
};