I've written that code, thinking that Union types were possible this way:
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;
}
But I get the following error:
Using tsc v1.4.1
error TS2322: Type 'boolean' is not assignable to type '[string, boolean]'. Property '0' is missing in type 'Boolean'.
So I guess it is not possible to have a function returning either a boolean or a string, do I must use any
?
Doc TS: http://blogs.msdn.com/b/typescript/archive/2014/11/18/what-s-new-in-the-typescript-type-system.aspx
In the meantime, I will use any
The reasoning for union types is for allowing for different parameter types, not for return values.
Think of the use case of union types as overloads for functions.
Take for example the use case in the link you provided:
function formatCommandline(c: string[]|string) {...
But if you try to apply that a function can return multiple types then it makes that function difficult for callers of that function difficult to use.
I would consider having multiple functions named in a way that would indicate the functionality that each provides.