我寫的代碼,以爲聯合類型是可能是這樣的:打字稿錯誤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
您可以聲明返回類型爲'string',並在出錯時返回'null'。 – Paleo
'[string,boolean]'是一個元組類型,一個在位置0有一個「字符串」,在位置1有一個「布爾值」。聯合類型是'string | boolean'。 – Fenton
對!所以有可能返回一個可能有一種或另一種類型的變量,這只是我寫這個錯誤的方法,不是嗎?我已經嘗試過,它的工作原理。 – Vadorequest