简体   繁体   English

如何在typescript中设置map密钥?

[英]How to set map key in typescript?

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.我通过应用 typescript 使用 reactjs。我在 map 中使用,但是如果我给键一个唯一的数值,就会发生错误。 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 |类型“Number”不可分配给类型“Key | null | 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' “number”是原语,但“Number”是包装器 object。尽可能使用“number”。ts(2322) index.d.ts(138, 9):预期类型来自属性“key”,它是在此处声明类型为“IntrinsicAttributes & LinkProps & RefAttributes”

Use number instead of Number.使用数字而不是数字。 "Number" with a capital N isn't the datatype you're looking for.大写 N 的“数字”不是您要查找的数据类型。 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.您应该尝试养成仔细阅读收到的错误消息的习惯,而不是仅仅被它吓到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM