问题描述
在 React (Preact,实际上) 类中,我希望在单击列的标题标题时对数据列进行排序。
这里是定义数据列的接口:
interface AllExisting {
id: number;
date: string;
short: string;
original: string;
}
这是进行排序的函数:
const doSortColumn = (a: AllExisting,b: AllExisting) => {
if (typeof a[sortColumn] === 'string') {
return a[sortColumn]?.localeCompare(b[sortColumn]);
} else if (a[sortColumn] !== undefined) {
return +a[sortColumn] - +b[sortColumn];
}
};
allExisting.sort(doSortColumn).map((r) => <TableRow row={r} onEdit={this.handleEdit} />)}
问题:
函数内 a[sortColumn]
和 b[sortColumn]
上的错误消息为:Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'AllExisting'. No index signature with a parameter of type 'string' was found on type 'AllExisting'. ts(7053)
以下是我尝试过的许多方法:
if (typeof a[(sortColumn as string | undefined)] === 'string') {
即使删除类型测试并仅使用 if (sortColumn !== undefined) {
仍然返回错误 Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'AllExisting'
(点击图片查看大图)
预期结果:
我更喜欢正确输入,但我也愿意在此功能中禁用打字稿(我该怎么做?)。
谢谢!
更新:
This answer thread 似乎包含魔法解决方案,但我不能完全算出正确的咒语。这看起来最有希望:
和
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)