[英]Typescript error : Element implicitly has an 'any' type because expression of type 'string' can't be used to index
I'm new to typescript and I met an error I can't understand after finding an online tuto to sort data on Reactjs with react hooks.我是 typescript 的新手,在找到一个使用反应挂钩对 Reactjs 上的数据进行排序的在线教程后,我遇到了一个我无法理解的错误。 Here the part of my component code where I get the error:
这是我收到错误的组件代码部分:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引
Job.tsx:作业.tsx:
export default function Jobs() {
const [data, setData] = useState([])
const [sortType, setSortType] = useState('name')
useEffect(() => {
const sortArray = (type: string) => {
const types = {
jobName: 'jobName',
created: 'created',
modified: 'modified'
}
const sortProperty = types[type]
const sorted = [...tasks].sort(
(a, b) => new Date(b[sortProperty]) - new Date(a[sortProperty])
)
console.log(sorted)
setData(sorted)
}
sortArray(sortType)
}, [sortType])
return (
<div className="font-bold">Sort by:</div>
<select
onChange={(e) => setSortType(e.target.value)}
className="text-center px-5 bg-gray-200 rounded-xl"
>
<option value="id">Id</option>
<option value="jobName">Job name</option>
<option value="created">Newest</option>
<option value="modified">Last modified</option>
</select>
<div>({tasks.length} users)</div>
{data.map((task) => (
<tr
key={task.id}
className="tableau text-center cursor-pointer"
onClick={() => router.push(`/job/${task.id}`)}
>
<td className="py-3">{task.jobName}</td>
<td className="py-3">
<div className="flex items-center gap-5 justify-center">
{task.created}
</div>
</td>
<td className="py-3">
<div className="flex items-center gap-5 justify-center">
{task.modified}
</div>
</td>
))}
)
}
The error message is telling you that the type of the sortProperty variable is string, but it is being used to index into an object. So you will need to update the types object to have an index signature like this错误消息告诉您 sortProperty 变量的类型是字符串,但它被用于索引 object。因此您需要更新类型 object 以具有这样的索引签名
interface StringIndexedObject {
[key: string]: string;
}
const types: StringIndexedObject = {
jobName: 'jobName',
created: 'created',
modified: 'modified',
};
This will allow you to use a string to index into the types object and the correct type will be inferred for the resulting value.这将允许您使用字符串来索引类型 object,并且将为结果值推断出正确的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.