Skip to content

Allow JSX.Element to take a generic parameter for more control over the return type.Β #43343

@SCLeoX

Description

@SCLeoX

Suggestion

πŸ” Search Terms

JSX, JSX.Element, TSX, React

βœ… Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

JSX.Element is used to determine the return type of a jsx tag. For example, if I have:

declare namespace JSX {
  type Element = string;
  type IntrinsicElements = { test: {} }
}

When I write

const a = <test/>;

The type of a is string.

I hope instead of always returning JSX.Element, it can return something like JSX.Element<"test">. (i.e. type of the tag name is passed in as a generic parameter.)

πŸ“ƒ Motivating Example

I am trying to use tsx without React. I get everything else working, except I have to define JSX.Element as HTMLElement. Which means, when I write

const myElement = <a href="#">Hello</a>;

The type of myElement is HTMLElement, instead of (ideally) HTMLAnchorElement.

If this feature is implemented, I can then write:

declare namespace JSX {
  type Element<T extends string> = T extends keyof HTMLElementTagNameMap
    ? HTMLElementTagNameMap[T]
    : HTMLElement;
}

As a result, myElement in the above example should have type HTMLAnchorElement instead of a boring HTMLElement.

πŸ’» Use Cases

The current workaround I am using is do a type cast after every JSX tag, which is not that ideal.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions