我是TS的新手,我想知道为什么我在以下代码中遇到类型错误(简化):

"use client";

import { ArrowDownWideNarrow, Settings } from "lucide-react";

interface LinkItemProps {
  name: string;
}

const iconMap = {
  Categories: <ArrowDownWideNarrow />,
  Admin: <Settings />,
};

export const LinkItem = ({ name }: LinkItemProps) => {
  <div>
    {iconMap[name]}
  </div>
}

错误在`{iconMap[名称]}中:

"Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ Categories: Element; Admin: Element; }'.

No index signature with a parameter of type 'string' was found on type '{ Categories: Element; Admin: Element; }'."

parent element拥有以下功能:

const LINKS = [
  {
    href: "/admin",
    name: "Admin",
    id: "admin",
  },
  {
    href: "/categories",
    name: "Categories",
    id: "categories",
  },
];

export const Sidebar = async () => {
  return (
    <div>
      {LINKS.map((link) => (
        <div key={link.href}>
          <LinkItem href={link.href} id={link.id} name={link.name} />
        </div>
      ))}
    </div>
  )
}

推荐答案

在类型‘{Categories:Element;Admin:Element;}’上未找到参数类型为‘STRING’的索引签名."

string类型太过wide,您可以更具体地说明nameprops 类型,这样它就可以正确地继承基于iconMap对象的字段.

100

interface LinkItemProps {
  name: keyof typeof iconMap;
}

或者是一种手动、严格键入的方法:

interface LinkItemProps {
  name: 'Categories' | 'Admin';
}

100

Typescript相关问答推荐

当类型断言函数返回假时,TypScript正在推断从不类型

TypScript ' NoInfer '类型未按预期工作

使用ngrok解析Angular 时出现HTTP故障

Redux—Toolkit查询仅在不为空的情况下添加参数

根据另一个属性的值来推断属性的类型

如何在Typescript 中输入两个相互关联的变量?

类型脚本`Return;`vs`Return unfined;`

如何按不能保证的功能过滤按键?

使用Dockerfile运行Vite React应用程序时访问env变量

如何在Type脚本中动态扩展函数的参数类型?

如何合并两个泛型对象并获得完整的类型安全结果?

如何缩小函数的返回类型?

从route.参数获取值.订阅提供";无法读取未定义";的属性

与toast.error一起react 中的Async TUNK错误消息

使用来自API调用的JSON数据的Angular

为什么类型脚本使用接口来声明函数?他的目的是什么.

类型';只读<;部分<;字符串|记录<;字符串、字符串|未定义&>';上不存在TS 2339错误属性.属性&q;x&q;不存在字符串

如何在TypeScript中描述和实现包含特定属性的函数?

Angular另一个组件的nativeelement未定义

Typescript 子类继承的方法允许参数中未定义的键