【问题标题】:Why doesn't TypeScript infer the return type of this JSX factory?为什么 TypeScript 不推断这个 JSX 工厂的返回类型?
【发布时间】:2019-05-28 00:48:23
【问题描述】:

JSX 工厂:

function h(type: string, _props, ..._children): HTMLElement {
    return document.createElement(type); // breakpoint here is hit
}

tsconfig.json:

"jsx": "react",
"jsxFactory": "h"

.tsx 文件中的用法:

const element = <div></div>; // = any

TypeScript 似乎没有从 JSX 工厂推断返回类型 (HTMLElement)。变量element 在这里是any 类型,这是不可取的。

我已经在 Visual Studio 2017 和 VS Code 中对此进行了测试。

我想知道是否可以让 TypeScript 推断 JSX 工厂的返回类型。如果不可能,这是 TypeScript 的限制吗?为什么?

【问题讨论】:

  • ts 应该没有问题。也许你的工厂功能的位置不好......
  • @JurajKocan 我将它用作全局函数。我目前在any 中看到的项目不使用模块、导入、导出等。只是一堆全局 *.tsx 文件。

标签: typescript jsx type-inference tsx


【解决方案1】:

TypeScript 手册规定如下:

JSX 结果类型

默认情况下,JSX 表达式的结果类型为 any。您可以通过指定 JSX.Element 接口来自定义类型。但是,无法从此接口检索有关 JSX 的元素、属性或子项的类型信息。这是一个黑盒子。

https://www.typescriptlang.org/docs/handbook/jsx.html#the-jsx-result-type

【讨论】:

    猜你喜欢
    • 2021-07-17
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-20
    相关资源
    最近更新 更多