웹사이트 검색

상태 사용 - React Typescript: 인덱스 표현식이 'number' 타입이 아니기 때문에 요소에 암묵적으로 'any' 타입이 있습니다


나는 간단한 투표 앱을 만들려고 하고 있습니다. 내 앱은 잘 작동합니다. 나는 내 앱을 타입스크립트로 만들기로 결정했습니다. 나는 타입스크립트 초급 수준입니다.

그때 나는 문자열 배열을 앱 컴포넌트에 전달합니다. 그런 다음 가장 많이 투표된 항목을 가져오고 가장 많이 투표된 나의 문자열을 연결하는 정렬 함수를 만듭니다.

하지만 문제는 제가 문자열을 mostVoted 정렬 함수에 연결할 때 TypeScript 오류가 발생한다는 것입니다.

요소는 인덱스 표현식이 'number' 타입이 아니기 때문에 암묵적으로 'any' 타입을 가집니다

또한 제가 상태를 만들 때 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에 공유합니다

답변 #1

문제는 anecdotes가 숫자가 필요로 하는 배열인데, mostVoted가 숫자가 아니라는 것입니다. 객체의 키는 항상 문자열이기 때문입니다(숫자 타입을 객체 키로 사용할 수 있는 방법이 있나요? 참조). 이로 인해 발생하는 오류입니다.

문제를 해결하려면 mostVoted를 정수로 파싱하여 사용할 수 있습니다:

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,
});

답변 #2

코멘트와 함께 언급하신 것처럼 크리스티나

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

그래서 anecdotes는 인덱스(숫자)를 기대하지만, mostVoted 함수는 문자열을 반환합니다. 최종 값이 투표 수이고 숫자라는 것을 알고 있더라도, 컴파일러는 그것을 알지 못합니다.

샌드박스를 보면 mostVoted가 문자열로 표현되어 있는 것을 볼 수 있습니다. 형 변환을 하면 오류가 사라지는 것을 볼 수 있습니다.

관련기사