Typescript error : Element implicitly has an 'any' type because expression of type 'string' can't be used to index

huangapple go评论83阅读模式
英文:

Typescript error : Element implicitly has an 'any' type because expression of type 'string' can't be used to index

问题

我对TypeScript还很陌生我在找了一个关于在Reactjs中使用React钩子对数据进行排序的在线教程后遇到了一个我无法理解的错误以下是我在组件代码中遇到错误的部分

Job.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>
              ))}
)
}
英文:

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. 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 :

export default function Jobs() {
const [data, setData] = useState([])
const [sortType, setSortType] = useState(&#39;name&#39;)
useEffect(() =&gt; {
const sortArray = (type: string) =&gt; {
const types = {
jobName: &#39;jobName&#39;,
created: &#39;created&#39;,
modified: &#39;modified&#39;
}
const sortProperty = types[type]
const sorted = [...tasks].sort(
(a, b) =&gt; new Date(b[sortProperty]) - new Date(a[sortProperty])
)
console.log(sorted)
setData(sorted)
}
sortArray(sortType)
}, [sortType])
return (
&lt;div className=&quot;font-bold&quot;&gt;Sort by:&lt;/div&gt;
&lt;select
onChange={(e) =&gt; setSortType(e.target.value)}
className=&quot;text-center px-5 bg-gray-200 rounded-xl&quot;
&gt;
&lt;option value=&quot;id&quot;&gt;Id&lt;/option&gt;
&lt;option value=&quot;jobName&quot;&gt;Job name&lt;/option&gt;
&lt;option value=&quot;created&quot;&gt;Newest&lt;/option&gt;
&lt;option value=&quot;modified&quot;&gt;Last modified&lt;/option&gt;
&lt;/select&gt;
&lt;div&gt;({tasks.length} users)&lt;/div&gt;
{data.map((task) =&gt; (
&lt;tr
key={task.id}
className=&quot;tableau text-center cursor-pointer&quot;
onClick={() =&gt; router.push(`/job/${task.id}`)}
&gt;
&lt;td className=&quot;py-3&quot;&gt;{task.jobName}&lt;/td&gt;
&lt;td className=&quot;py-3&quot;&gt;
&lt;div className=&quot;flex items-center gap-5 justify-center&quot;&gt;
{task.created}
&lt;/div&gt;
&lt;/td&gt;
&lt;td className=&quot;py-3&quot;&gt;
&lt;div className=&quot;flex items-center gap-5 justify-center&quot;&gt;
{task.modified}
&lt;/div&gt;
&lt;/td&gt;
))}
)
}

答案1

得分: 1

错误消息告诉您,sortProperty变量的类型是字符串,但它被用于索引对象。因此,您需要更新types对象,使其具有这样的索引签名

interface StringIndexedObject {
    [key: string]: string;
}

const types: StringIndexedObject = {
    jobName: 'jobName',
    created: 'created',
    modified: 'modified',
};

这将允许您使用字符串来索引types对象,并且将为生成的值推断出正确的类型。

英文:

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

interface StringIndexedObject {
[key: string]: string;
}
const types: StringIndexedObject = {
jobName: &#39;jobName&#39;,
created: &#39;created&#39;,
modified: &#39;modified&#39;,
};

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.

huangapple
  • 本文由 发表于 2023年1月9日 02:26:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75050320.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定