2016-04-21 103 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版本中清除它!