Weboldal keresés

use state - React Typescript: Az elem implicit módon 'any' típusú, mert az index kifejezés nem 'number' típusú


Próbálok készíteni egy egyszerű szavazóalkalmazást. Az alkalmazásom jól működik. Úgy döntöttem, hogy Typescriptben készítem az alkalmazásomat. Kezdő szinten vagyok a Typescriptben.

Aztán tömböket adok át stringekből az alkalmazás komponensnek. Létrehozok egy rendezési függvényt, ahol a legtöbb szavazatot kapott elemhez csatolom a legtöbbet szavazott stringemet.

De a probléma az, hogy TypeScript hibát kapok, amikor a stringemet a mostVoted rendezési függvényhez csatolom.

Az elem implicit módon 'any' típusú, mert az index kifejezés nem 'number' típusú

Emellett létrehozok egy állapotot, ahol a any-t használtam. Nem tudom, mit kellene definiálnom az állapotra a any helyett.

Ez az állapot

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

Ez az egész kódom

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"));

Megosztom a kódom a codesand-boxban

Válasz #1

A probléma az, hogy az anecdotes egy tömb, amely számot igényel az indexeléshez, de a mostVoted nem szám, mert egy objektum kulcsai mindig stringek (lásd: Van-e mód arra, hogy numerikus típusú értéket használjunk objektumkulcsként?). Ez eredményezi a kapott hibát.

A probléma megoldásához a mostVoted-et át tudod alakítani int típusra, és így használhatod:

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

Az állapot típusára vonatkozóan így írhatja:

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

Válasz #2

Krisina, ahogy említetted a kommentekkel

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

Tehát az anecdotes egy indexet (számot) vár, de a mostVoted függvény egy karakterláncot ad vissza. Még ha tudod is, hogy a végső érték a szavazatok száma és szám, a fordító nem tudja ezt.

Ha megnézed a homokozót, látni fogod, hogy a mostVoted karakterláncként van ábrázolva. Átkonvertálhatod, és látni fogod, hogy a hiba eltűnik.

Kapcsolódó cikkek