打字稿 无法分配类型 '{ [键: 字符串]: 字符串; }[]' 键入"T[]"



我有一个独立的助手函数,它允许通过字符串键过滤对象数组:

function filterRows(
rows: Array<{ [key: string]: string }>,
searchKey: string
) {
return rows.filter((obj) =>
Object.keys(obj).some((key) => obj[key].toString().includes(searchKey))
);
}

在组件中,我有一个类型为Array<T>(组件推断类型(的变量TableRowsCells

所以,这个变量可以有值;示例:

const TableRowsCells = [
{
firstname: 'John',
lastname: 'Adams'
},
{
firstname: 'Paul',
lastname: 'Walker'
},
];

const TableRowsCells = [
{
company: 'Vody aho',
nb_employees: 1590,
country: 'Hong Kong'
},
{
company: 'Royal spirit',
nb_employees: 15,
country: 'USA'
},
];

现在我想使用上面的辅助函数过滤这个变量:

type EnhancedTableProps<T> = {
TableRowsCells: Array<T>;
searchKey?: string;
};
function EnhancedTable<T>({ TableRowsCells, searchKey }: EnhancedTableProps<T>) {
/** Code stuff...**/
let outputRowsItems = TableRowsCells;
if (typeof searchKey === 'string' && searchKey.length > 2) {
outputRowsItems = filterRows(TableRowsCells, searchKey);
}
/** Code stuff...**/
}

像这样,我有两个打字脚本错误:

错误1(outputRowsItems中的outputRowsItems = filterRows(TableRowsCells, searchKey);(:

Cannot assign type '{ [key: string]: string; }[]' to type 'T[]'.
Cannot assign type '{ [key: string]: string; }' to type 'T'.
'T' could have been instantiated with an arbitrary type which may not be related to '{ [key: string]: string; }'.ts(2322)

错误2(TableRowsCell中的outputRowsItems = filterRows(TableRowsCells, searchKey);(:

(parameter) TableRowsCells: T[]
Argument of type 'T[]' is not assignable to parameter of type '{ [key: string]: string; }[]'.
Cannot assign type 'T' to type '{ [key: string]: string; }'.ts(2345)

最后,我希望outputRowsItems具有与TableRowsCells相同的类型,即Array<T>

你能帮我解决这些错误吗?

游乐场链接

thx

您可以执行类似于-的操作

type TableRowsCells = Array<Record<string, string | number>>;
type SearchKey = string;
type EnhancedTableProps = {
TableRowsCells: TableRowsCells,
searchKey?: SearchKey;
};
function filterRows(
rows: TableRowsCells,
searchKey: SearchKey
) {
return rows.filter((obj) =>
Object.keys(obj).some((key) => obj[key].toString().includes(searchKey))
);
}
function EnhancedTable({ TableRowsCells, searchKey }: EnhancedTableProps) {
/** Code stuff...**/
let outputRowsItems = TableRowsCells;
if (typeof searchKey === 'string' && searchKey.length > 2) {
outputRowsItems = filterRows(TableRowsCells, searchKey);
}
/** Code stuff...**/
}

游乐场链接

要保留输入的类型,需要为filterRows使用通用类型参数

function filterRows<T extends Record<keyof T, string>>(
rows: Array<T>,
searchKey: string
) {
return rows.filter((obj) =>
Object.keys(obj).some((key) => obj[key as keyof T].toString().includes(searchKey))
);
}

游乐场链接

最新更新