Skip to content

Minor performance issue when using HTMLElementTagNameMapΒ #63347

@jasonlyu123

Description

@jasonlyu123

πŸ”Ž Search Terms

HTMLElementTagNameMap
performance

πŸ•— Version & Regression Information

  • This changed between versions 5.9.3 and 6.0.2

⏯ Playground Link

https://www.typescriptlang.org/play/?#code/GYVwdgxgLglg9mABAWwIYAcCiAbAps3MKAHgGlFcAPKQgEwGdEBrXATzmEQAkAVAWQAyOfISg9UAcwByqAnwwA+ABS48BIgC5EpAJRbeg4erGSZcjAG1SAXQBQoSLAQoMR0WQrU6jFu04BlADUAcTcicWlZXHl0RGVVEU1tPUQg0LVRCLNoyxt7cGh4JDQsDKIVMqgtVDBWFIMhSsQAb1tERAAnXCgQDqRaOAgQYwA6CC7UGjCoCsSoHQBuWwBfW1tUQoQlEumlAHJaGAA3PZ1FtYdNpA2nMFn9fka5nRaV9qA

πŸ’» Code

function mapElement<K extends keyof HTMLElementTagNameMap>(element: K): HTMLElementTagNameMap[K]
function mapElement<K extends keyof SVGElementTagNameMap >(element: K): SVGElementTagNameMap[K]
function mapElement(element: any): HTMLElement {
  return document.createElement(element);
}

action(mapElement('div'));

function action(ele: HTMLElement) {
}  

πŸ™ Actual behavior

The type check for this specific overload is slower in TypeScript 6.0, but still bearable (under 50ms on a modern PC). From the flame graph, it seems like the hot path is

https://github.com/microsoft/TypeScript/blob/7b8cb3bdf82f400642b73173f941335775d6f730/src/compiler/checker.ts#L25342

This also seems to happen in TypeScript 7, but I can't reliably reproduce it. It doesn't happen on my Windows machine, but on my Linux machine.

Although this seems minor, it is a bit odd that TypeScript needed to create a union of all the HTML elements, comparing all the properties to choose an overload. If this doesn't match the merge criteria, maybe it can still be improved in TypeScript 7? Or maybe there is another way to type this function that won't trigger this?

πŸ™‚ Expected behavior

performance improvement.

Additional information about the issue

For context, this issue was found in our performance smoke test in https://github.com/sveltejs/language-tools. It consistently failed with TypeScript 6. The virtual code for the Svelte file includes a svelteHTML.mapElementTag('div') function call. The function is similar to the reproduction, just that it uses the deprecated ElementTagNameMap.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Not a DefectThis behavior is one of several equally-correct options

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions