首页 文章

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

提问于
浏览
0

我编写了那段代码,认为Union类型可能是这样的:

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 回答

  • 1

    联合类型的推理是允许不同的参数类型,而不是返回值 .

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

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

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

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

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

相关问题