2015-04-07 140 views
0

我寫的代碼,以爲聯合類型是可能是這樣的:打字稿錯誤TS2322:在函數返回聯盟類型值

public static template(templateName, data): [string, boolean]{ 
     var templateFullPath = Template.basePath + Template.templatesFolder + '/' + templateName + Template.templatesAfter + Template.ext; 
     if(Template.exists(templateFullPath)){ 
      try{ 
       return (Template._load(templateFullPath))(data); 
      }catch(e){ 
       console.error('Template ' + templateFullPath + ' could not be loaded.'); 
       console.error(e); 
      } 
     }else{ 
      console.error('Template ' + templateFullPath + ' could not be found.'); 
     } 

     return false; 
    } 

,但我得到了以下錯誤:

Using tsc v1.4.1

error TS2322: Type 'boolean' is not assignable to type '[string, boolean]'. Property '0' is missing in type 'Boolean'.

所以我想這是不可能有一個函數返回一個布爾或字符串,我必須使用any

文件TS:http://blogs.msdn.com/b/typescript/archive/2014/11/18/what-s-new-in-the-typescript-type-system.aspx

在此期間,我將使用any

+0

您可以聲明返回類型爲'string',並在出錯時返回'null'。 – Paleo

+3

'[string,boolean]'是一個元組類型,一個在位置0有一個「字符串」,在位置1有一個「布爾值」。聯合類型是'string | boolean'。 – Fenton

+0

對!所以有可能返回一個可能有一種或另一種類型的變量,這只是我寫這個錯誤的方法,不是嗎?我已經嘗試過,它的工作原理。 – Vadorequest

回答

1

的理由union類型是允許不同的參數類型,而不是返回值。

將聯合類型的用例視爲函數的重載。

就拿用例中您所提供的鏈接:

function formatCommandline(c: string[]|string) {... 

但是,如果你嘗試應用該函數可以返回多個類型,然後它使得該功能難以使用的來電該功能難。

我會考慮以一種方式命名多個函數,以指出每個函數提供的功能。

+0

感謝您的確認! – Vadorequest