React Typescript:元素隐式具有 'any' 类型,因为索引表达式不是 'number' 类型

React Typescript: Element implicitly has an 'any' type because index expression is not of type 'number'

我正在尝试制作一个简单的投票应用程序。我的应用程序运行良好。我决定用 Typescript 制作我的应用程序。我是 Typescript 的初学者。

然后我将字符串数组传递给应用程序组件。我创建了一个排序函数,它将获得最多投票并附上我获得最多投票的字符串。

但问题是当我使用 mostVoted 排序函数附加我的字符​​串时出现打字稿错误。

Element implicitly has an 'any' type because index expression is not of type 'number

我还创建了一个我使用过的状态 any。我不知道我应该定义什么状态而不是 any .

这是状态

 const [votes, setVotes] = useState<any>({
    // what should I define my state instead of any
    0: 0,
    1: 0,
    2: 0,
    3: 0,
    4: 0,
    5: 0,
  });

这是我的全部代码

import React, { useState } from "react";
import ReactDOM from "react-dom";

const anecdotes: string[] = [
  "If it hurts, do it more often",
  "Adding manpower to a late software project makes it later!",
  "The first 90 percent of the code accounts for the first 90 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.",
  "Any fool can write code that a computer can understand. Good programmers write code that humans can understand.",
  "Premature optimization is the root of all evil.",
  "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.",
];

interface Props {
  title?: string;
  anecdote?: string;
  numVotes?: number;
}

const Anecdote = ({ title, anecdote, numVotes }: Props) => (
  <>
    <h1>{title}</h1>
    <div>{anecdote}</div>
    <div>Has {numVotes} votes</div>
  </>
);

interface AppProps {
  anecdotes: string[];
}

const App = ({ anecdotes }: AppProps) => {
  const [selected, setSelected] = useState<number>(0);
  const [votes, setVotes] = useState<any>({
    // what should I define my state instead of any
    0: 0,
    1: 0,
    2: 0,
    3: 0,
    4: 0,
    5: 0,
  });

  const mostVoted = Object.keys(votes).sort((a, b) => votes[b] - votes[a])[0]; // Element implicitly has an 'any' type because index expression is not of type 'number'.
  console.log(Object.keys(votes).sort((a, b) => votes[b] - votes[a]));

  const getRandomIndex = () => Math.floor(Math.random() * anecdotes.length);

  const handleNextAnecdote = () => {
    let idx = getRandomIndex();
    while (idx === selected) {
      idx = getRandomIndex();
    }
    setSelected(idx);
  };

  const addVote = () => {
    setVotes({
      ...votes,
      [selected]: votes[selected] + 1,
    });
  };

  return (
    <>
      <Anecdote
        title={"Anecdote of the day"}
        anecdote={anecdotes[selected]}
        numVotes={votes[selected]}
      />
      <button onClick={handleNextAnecdote}>Next anecdote</button>
      <button onClick={addVote}>Vote</button>
      <Anecdote
        title={"Anecdote with most votes"}
        anecdote={anecdotes[mostVoted]} // In here I am getting typescript Error.
        numVotes={votes[mostVoted]}
      />
    </>
  );
};

ReactDOM.render(<App anecdotes={anecdotes} />, document.getElementById("root"));

我在codesand-box

中分享我的代码

问题是 anecdotes 是一个需要数字索引的数组,但 mostVoted 不是数字,因为对象的键总是字符串(参见 Is there any way to use a numeric type as an object key?).这会导致您收到错误。

要解决此问题,您可以将 mostVoted 解析为一个 int 并使用它:

const mostVoted = parseInt(Object.keys(votes).sort((a, b) => votes[b] - votes[a])[0], 10);

关于你的状态类型你可以写成

const [votes, setVotes] = useState<{[key: string]: number}>({
  0: 0,
  1: 0,
  2: 0,
  3: 0,
  4: 0,
  5: 0,
});

你在评论中提到的 Krisina

// Element implicitly has an 'any' type because index expression is not of type 'number'.

所以 anecdotes 需要一个索引(数字),但是 mostVoted 函数 returns 一个字符串。即使你知道最终的值是票数和一个数字,编译器也不知道。

如果您查看沙箱,您会发现 mostVoted 表示为字符串。你可以转换它,你会看到错误消失了。