微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Typescript 如何在 React 问题:以下是我尝试过的许多方法:预期结果:

如何解决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)

view error message

以下是我尝试过的许多方法

if (typeof a[(sortColumn as string | undefined)] === 'string') {

error3

a[(sortColumn as any)]

view error message

即使删除类型测试并仅使用 if (sortColumn !== undefined) { 仍然返回错误 Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'AllExisting' (点击图片查看大图)

error4

预期结果:

我更喜欢正确输入,但我也愿意在此功能中禁用打字稿(我该怎么做?)。

谢谢!

更新:

This answer thread 似乎包含魔法解决方案,但我不能完全算出正确的咒语。这看起来最有希望:

attempt 71

这似乎有效,但现在显示行的行有以下两个错误

attempt 71e1

attempt 71e2

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。