为什么TypeScript无法推断此JSX工厂的返回类型?

时间:2018-12-31 13:53:58

标签: typescript jsx type-inference tsx

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中对此进行了测试。

A tooltip in Visual Studio 2017 says "const element: any"

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

1 个答案:

答案 0 :(得分:0)

TypeScript手册规定以下内容:

  

JSX结果类型

     

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

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