首页 > 解决方案 > 合并反应打字稿命名空间声明

问题描述

我正在使用带有 Typescript 的 React。目前@types/react 提供的 ReactElement 定义是错误的——它们不允许 ReactElement 是例如字符串或数字。据我了解,由于向后兼容性,这不会被修复。

因此,我认为我可以在本地修复这些声明,但我无法使其工作。这是我尝试过的:

我有一个global.d.ts文件,我在其中保留了一些额外的声明(如扩展窗口等)。我添加了这段代码:

declare namespace React {
  type ReactElement<
    P = any,
    T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>
  > =
    | {
        type: T
        props: P
        key: Key | null
      }
    | React.ReactNode
}

所以基本上我希望 ReactElement 也包含 React.ReactNode 声明。

原始 ReactElement 声明如下:

declare namespace React {
...
  interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>> {
      type: T;
      props: P;
      key: Key | null;
  }
...
}

标签: reactjstypescript

解决方案


推荐阅读