如何解决Typescript 如何在 React 问题:以下是我尝试过的许多方法:预期结果:
在 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 举报,一经查实,本站将立刻删除。