Search code examples
typescriptjsxtype-inferencetsx

Why doesn't TypeScript infer the return type of this JSX factory?


JSX factory:

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

tsconfig.json:

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

Usage in .tsx file:

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

TypeScript doesn't seem to infer the return type (HTMLElement) from the JSX factory. The variable element is of type any here, which isn't desirable.

I have tested this in both Visual Studio 2017 and VS Code.

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

I am wondering if it's possible to make TypeScript infer the return type of the JSX factory. If it's not possible, is this a TypeScript limitation and why?


Solution

  • The TypeScript handbook states the following:

    The JSX result type

    By default the result of a JSX expression is typed as any. You can customize the type by specifying the JSX.Element interface. However, it is not possible to retrieve type information about the element, attributes or children of the JSX from this interface. It is a black box.

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