React Typescript:元素隐式具有“任何”类型,因为索引表达式不是“数字”类型

克里希纳

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

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

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

元素隐式具有“任何”类型,因为索引表达式不是“数字”类型

我还创建了一个我使用的状态any我不知道我应该定义 state 而不是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"));

我在codeand-box 中分享我的代码

彼得·莱恩哈特

问题是这anecdotes是一个数组,它需要一个数字来索引它,但mostVoted它不是一个数字,因为对象的键总是字符串(请参阅有没有办法将数字类型用作对象键?)。这会导致您得到错误。

要解决该问题,您可以解析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,
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

带有React> Element的Typescript隐式具有'any'类型,因为类型'string'的表达式不能用于索引

React Typescript:元素隐式地具有“ any”类型,因为类型没有索引签名

全局窗口对象:元素隐式具有“任何”类型,因为索引表达式不是“数字”类型。ts

Typescript-React State:元素隐式具有“ any”类型,因为类型“ State”没有索引签名

元素隐式具有“ any”类型,因为索引表达式不是“ number”类型[7015]

TypeScript TS7015:元素隐式地具有“ any”类型,因为索引表达式不是“ number”类型

元素隐式具有“任何”类型,因为索引表达式不是“数字”类型的打字稿 - 从数组中获取单个键

React Typescript - 绑定元素“C”隐式具有“任何”类型。TS7031

Graphql React Typescript 错误绑定元素“货币”隐式具有“任何”类型

元素隐式具有 'any' 类型,因为类型 'string' 的表达式不能用于索引类型 '{ AT: number; 是:数字,...}`

元素隐式具有“任何”类型,因为“数字”类型的表达式不能用于索引类型“{}”。.ts(7053) VUEJS

元素隐式地具有“ any”类型,因为索引表达式不是“ number”类型。-索引签名错误

Typescript错误:元素隐式具有“ any”类型,因为类型“ string”的表达式不能用于索引类型

TypeScript - 元素隐式具有“any”类型,因为“storyFile”类型的表达式不能用于索引类型“{}”

TypeScript:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型

Build:元素隐式地具有“ any”类型,因为索引表达式不是“ number”类型

元素隐式具有“任何”类型,因为“字符串”类型的表达式

隐式具有“任何”类型,因为 typescript 中的类型表达式

Object.keys迭代导致Typescript错误“元素隐式具有'any'类型,因为索引表达式不是'number'类型”

元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引“类型”类型

反应打字稿错误 - 元素隐式具有任何类型,因为类型字符串的表达式不能用于索引类型 {}

打字稿“元素隐式具有'任何'类型,因为'Rank'类型的表达式不能用于索引类型'IPowerCards'”

Angular - 元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型

如何修复元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型?

TS7053:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引“User_Economy”类型

TS7053:元素隐式具有“任何”类型,因为“页面”类型的表达式不能用于索引类型“对象”

错误 TS7053:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引“模块类型”

元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引“Breakpoints”类型

元素隐式地具有“ any”类型,因为类型“ any”的表达式不能用于索引类型