Home > Back-end >  How to set map key in typescript?
How to set map key in typescript?

Time:04-07

I am using reactjs by applying typescript. I am using in the map, but if I give a unique numer value to the key, an error occurs. Anyone know why?

atom.js

export interface Person {
  id: Number;
  num: string;
  name: string;
  img: string;
}
....

export const filteredPersonList = selector({
  key: "filteredPersonListSelector",
  get: ({ get }) => {
    const filterType = get(filteredType);
    const filterSearch = get(filteredSearch);
    const person = get(person);

    if (filterSearch.length > 0 && filterType !== "all") {
      const filteredList = person
        .filter((p) =>p.name.includes(filterSearch))
        .filter((p) =>p.type.includes(filterType));
      return filteredList;
    } else if (filterSearch.length > 0 && filterType === "all") {

      return filteredList;
    } else if (filterType !== "all") {

      return filteredList;
    } else {
      return person;
    }
  },
});
import { Link } from "react-router-dom";
import { useRecoilState, useRecoilValue, useSetRecoilState } from "recoil";
import styled from "styled-components";
import {
filteredPersonList
} from "../store/atom";

interface TypeItemComp {
  currentType: boolean;
}

export default function Main() {
  const [filterType, setFilterType] = useRecoilState(filteredType);
  const people = useRecoilValue(filteredPersonList);

  return (
    <MainContainer>
      <PersonContainer>
        {people.map((p) => (
          <Link key={p.id} to={`/detail/${p.id}`}>. //an error occurs here

          </Link>
        ))}
      </PersonContainer>
    </MainContainer>
  );
}

The warning is as below.

Type 'Number' is not assignable to type 'Key | null | undefined'. Type 'Number' is not assignable to type 'number'. 'number' is a primitive, but 'Number' is a wrapper object. Prefer using 'number' when possible.ts(2322) index.d.ts(138, 9): The expected type comes from property 'key' which is declared here on type 'IntrinsicAttributes & LinkProps & RefAttributes'

CodePudding user response:

Use number instead of Number. "Number" with a capital N isn't the datatype you're looking for. It even says so in the error message.

I know error messages may look overwhelming sometimes, especially when you're just starting out as a programmer. But most of the time, they're awesome.

You should try and make a habit of carefully READING the error messages you get, instead of just being alarmed by it.

  • Related