2016-04-21 101 views
2

工作根据打字稿documentation(寻找字符串文字类型部分),下面的代码应该打字稿工作:打字稿字符串文字类型没有函数重载

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

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

当我运行代码,或一些更有意义的变化,对TypeScript Playground,或在Visual Studio中,我得到以下错误:

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

什么建议吗?在尝试在自己的代码上实现非常类似的东西后,我遇到了这个错误。

回答

1

您是否尝试从非专门签名开始?

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

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

```

+0

它的工作原理,谢谢!大! 你有任何解释为什么它的工作?我试图理解。 – FrancoSF

+1

不确定,也许是因为专门的签名无法看到它们之后的实现?更多细节[here](http://stackoverflow.com/a/32212966/3478605)。 –

0

回答我自己的问题: 恕我直言,泛型的使用可以解决这种更好的方式解决问题。

字符串文字+函数重载方法

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

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

var inputElement = createElement("input"); 

泛型接近

function createElement<elementType>(): elementType { /* ... */ } 

var inputElement = createElement<HTMLInputElement>(); 

泛型方法具有更强的类型约束

function createElement<elementType extends HTMLElement>(): elementType { /* ... */ } 

var inputElement = createElement<HTMLInputElement>(); 
0

如果您想限制为只有指定的字符串(例如,当其他情况是错误的时候),你显然必须首先对类型进行别名。

type ValidTagOptions = "img" | "input"; 
function createElement(tagName: ValidTagOptions): HTMLImageElement; 
function createElement(tagName: ValidTagOptions): HTMLInputElement; 

这是调用时触发一个编译器错误:

createElement("a"); // Error! 

你不能一开始就在函数签名的文字做,因为你发现了。恼人的,国际海事组织。我希望他们在将来的TS版本中清除它!