This repository was archived by the owner on Oct 12, 2022. It is now read-only.
This repository was archived by the owner on Oct 12, 2022. It is now read-only.
Using string literal types to distinguish overloads - Advanced Types Section - String Literal Types Subsection #235
Open
Description
Obviously the code in the handbook about using string literal types to distinguish overloads doesn't work out of the box, so I did my own tests using this code which looks like the one in the handbook:
class Element_ {
}
class HTMLImageElement_ extends Element_ {
constructor() {
super();
}
}
function createUIElement(tagName: "img"): HTMLImageElement_;
function createUIElement(tagName: string): Element_ {
switch (tagName) {
case 'img':
return new HTMLImageElement_();
default:
return new Element_();
}
}
The code above doesn't compile. VS Code will show the following compile error:
"Specialized overload signature is not assignable to any non-specialized signature."
I found two ways to fix this:
1- Use the default way of overloading and make a function that takes any
.
function createUIElement(tagName: "img"): HTMLImageElement_;
function createUIElement(tagName: string): Element_;
function createUIElement(tagName: any): Element_ {
switch (tagName as string) {
case 'img':
return new HTMLImageElement_();
default:
return new Element_();
}
}
2- Define an overload that takes a string
type of the function that already takes a string
.
function createUIElement(tagName: "img"): HTMLImageElement_;
function createUIElement(tagName: string): Element_; // if we remove this overload, we get the compile error
function createUIElement(tagName: string): Element_ {
switch (tagName) {
case 'img':
return new HTMLImageElement_();
default:
return new Element_();
}
}
Is this a handbook code error or a compiler error and the code in the handbook is correct?