FrancoSF FrancoSF - 2 months ago 30
TypeScript Question

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.

Answer

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 { /* ... */ }

```

Comments