Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript String Literal Types not working in function overloading

According to TypeScript documentation (look for the String Literal Types section), the following code should work on TypeScript:

function createElement(tagName: "img"): HTMLImageElement;
function createElement(tagName: "input"): HTMLInputElement;
// ... more overloads ...

function createElement(tagName: string): Element {
    // ... code goes here ...
}

When I run the code, or some more meaningful variation, on TypeScript Playground, or on Visual Studio, I get the following error:

Specialized overload signature is not assignable to any non-specialized signature.

Any suggestion? I came to this error after trying to implement something very similar on my own code.

like image 936
FrancoSF Avatar asked Jun 23 '26 15:06

FrancoSF


1 Answers

Did you try to start with a non specialized signature?

function createElement(tagName: string): Element;
function createElement(tagName: "img"): HTMLImageElement;
function createElement(tagName: "input"): HTMLInputElement;
// ... more overloads ...

function createElement(tagName: string): Element { /* ... */ }

```

like image 78
Valéry Avatar answered Jun 26 '26 04:06

Valéry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!