我正在定义三件事:

export interface MenuItemLink {
  to: string;
  label: string;
}

type MenuItem = JSX.Element | MenuItemLink;

export interface NavBarProps {
  menuItems: MenuItem[];
}

当我try 在 map 中使用它时

const items = menuItems.map((item, index) => {
    if (item?.to) {
      return (
        <Link to={item.to} key={index}>
          <span>{item.label}</span>
        </Link>
      );
    } else {
      return item;
    }
  });

它在item.to上给了我一个打字错误:

Property 'to' does not exist on type 'MenuItem'.
  Property 'to' does not exist on type 'Element'.ts(2339)

但它是MenuItemLink上的一个可用属性,这是MenuItem的可能类型之一,那么它为什么抛出这个错误呢?

推荐答案

你可以用'to' in item查一下wine 店的情况

const items = menuItems.map((item, index) => {
    if ('to' in item) {
      return (
        <Link to={item.to} key={index}>
          <span>{item.label}</span>
        </Link>
      );
    } else {
      return item;
    }
  });

如果menuItems是一个类的对象,那么您可以使用instanceof:https://www.typescriptlang.org/docs/handbook/2/narrowing.html#instanceof-narrowing

Typescript相关问答推荐

Angular 垫页分类和垫排序不起作用

替换类型脚本类型中的多个特定字符串

带有微前端的动态React路由问题

角形标题大小写所有单词除外

在Angular中注入多个BrowserModules,但在我的代码中只有一个

隐式键入脚本键映射使用

如何编写一个类型脚本函数,将一个对象映射(转换)为另一个对象并推断返回类型?

为什么我的条件类型不能像我预期的那样工作?

类型脚本满足将布尔类型转换为文字.这正常吗?

分解对象时出现打字错误

Vue3 Uncaught SyntaxError:每当我重新加载页面时,浏览器控制台中会出现无效或意外的令牌

从泛型类型引用推断的文本类型

有没有可能创建一种类型,强制在TypeScrip中返回`tyPeof`语句?

带投掷的收窄类型

如何在打字角react 式中补齐表格组

使用强类型元组实现[Symbol.iterator]的类型脚本?

可以用任意类型实例化,该类型可能与

Svelte+EsBuild+Deno-未捕获类型错误:无法读取未定义的属性(读取';$$';)

如何创建允许使用带有联合类型参数的Array.from()的TS函数?

Next 13 + React 18 createContext 类型的构建问题