打字稿错误TS2322:函数返回值中的联合类型

时间:2015-04-07 11:54:56

标签: typescript typescript1.4

我写了那段代码,认为联盟类型是可能的:

    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;
    }

但是我收到以下错误:

  

使用tsc v1.4.1

     

错误TS2322:类型'boolean'不能分配给'[string,boolean]'类型。     “布尔”类型中缺少属性“0”。

所以我想有一个函数返回布尔值或字符串是不可能的,我必须使用any吗?

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

在此期间,我将使用any

1 个答案:

答案 0 :(得分:1)

union类型的推理是允许使用不同的参数类型,而不是返回值。

将union类型的用例视为函数的重载。

以您提供的链接中的用例为例:

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

但是如果你尝试应用一个函数可以返回多个类型,那么它使得该函数的调用者很难使用该函数。

我会考虑以指示每个提供的功能的方式命名多个函数。

相关问题