TypeScript 2 TSX保留和noimplicitany错误TS2602:全局类型' JSX.Element'不存在

时间:2016-11-17 21:17:50

标签: typescript2.0 mithril.js tsx

我使用TypeScript 2和TSX使用保留(而不是React)设置并使用" noImplicitAny"启用:

"noImplicitAny": true,
"jsx": "preserve"

问题是,我在尝试构建一个简单的TSX文件时不断收到此错误:

error TS2602: JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist.

这是我的TSX文件的一个示例:

'use strict';

import m from './m';

export default {
  view() {
    return (
      <h1>Hello Mithril!</h1>
    );
  }
};

我试图让TSX使用非React堆栈(Mithril)。提前谢谢!

3 个答案:

答案 0 :(得分:1)

回答原问题:(如何解决TS2602错误)

这很简单,如explained here

  

正如错误所说:&#34;因为全局类型&#39; JSX.Element&#39;不存在&#34;

     

您可以定义这些类型:

declare namespace JSX {
  interface Element { }
  interface IntrinsicElements { div: any; }
}
  

我建议从DefinitelyTyped

获取react-jsx.d.ts文件

您可以使用this file作为更完整类型的来源(您需要为IntrinsicElements中的每个子元素定义,即divp,{{1等等。)

与TSX和Mithril进一步接触:

一旦您解决了打字问题,您就会发现自己并不存在。如果您使用a设置,HTML代码将直接写在生成的"jsx": "preserve"文件中,无需任何翻译。这当然不能通过网络浏览器加载(因为它是一个javascript文件,而不是一个html文件)。

我认为有两种方法可以让它发挥作用:

首先想到的解决方案是使用js并编写一个小包装器,将调用转发给mithril,如下所示:

"jsx":"react"

这是我目前正在使用的解决方案,因为它不涉及其他工具。

另一个解决方案是保留class React { public static createElement(selector: string, attributes: object, ...children: Mithril.Child[]): Mithril.Child { return m(selector, attributes, children); } } 并使用Babel as described in mithril documentation"jsx":"preserve"文件(由jsx文件中的typescript生成)转换为有效的tsx文件。

最后,我设法让它工作,但我发现这个过程相当混乱,使用typescript / npm模块系统阻碍了JSX类型扩展Mithril类型(这样你的函数可以返回mithril兼容类型)等我必须修改mithril typings(并下降npm js),并添加一些我自己的模块。

我有兴趣知道是否有人以优雅而简单的方式解决了这个问题!

答案 1 :(得分:1)

由于缺乏声誉,我不会让你对上面的答案发表评论,所以我会把它包含在我自己的答案中。

首先,您可以在项目的顶部包含this gist,并将其命名为mithril-jsx.d.ts,以便typescript将其视为类型定义,并且不会对其进行编译。链接的要点只需将JSX.element声明为m.Vnode<any, any>,并将JSX.IntrinsicElements下的每个HTML元素列为any。不是一件大事,而是节省时间。

第二,我甚至发布这个的原因:你需要gulp或任何其他工具来编译.tsx文件到mithril-using .js。您所要做的就是在tsconfig.json

中指定这些内容
{
  "compilerOptions": {
    //...your other stuff here
    "jsx": "react",
    "jsxFactory": "m"
  }
}

有关编译器选项的更多信息,请访问:http://www.typescriptlang.org/docs/handbook/compiler-options.html

答案 2 :(得分:0)

我还在开发Mithril(2.0.3)和TypeScript(3.5.3)。

TS7026: JSX element implicitly has type 'any' because no interface 'JSX.IntrinsicElements' exists.

可以通过安装@types/react来解决此错误消息。

npm install --save-dev @types/react

tsconfig.json具有以下设置。

{
  "compilerOptions": {
    "jsx": "react",
    "jsxFactory": "m"
  }
}