-1
myFuncResult interface {
  abc: string
}

function myFunc():myFuncResult {
 if(something) return { abc:'abc' } //ok here

 return 'result' //but this line gave me warning
}

我有两种基于条件的结果类型(对象和字符串),如何在我的界面中声明它?

4

2 回答 2

2

既然您要返回两种不同的类型/接口(可以是字符串,也可以是myFuncResult字符串),为什么不使用管道运算符来创建联合类型呢?

function myFunc(): myFuncResult | string {
    if (something)
        return { abc:'abc' };

    return 'result';
}

或者,您可以直接创建联合类型:

type myFuncResult = { abc: string } | string;

function myFunc(): myFuncResult {
    if (something)
        return { abc:'abc' };

    return 'result';
}
于 2020-03-11T07:07:33.457 回答
0

发生这种情况是因为string不等于接口类型myFuncResultmyFuncResult您可以使用abc变量返回类型:

myFunc(): myFuncResult {
    if (something) 
        return { abc:'abc' } //ok here    
    return {abc: 'result'} //but this line gave me warning
}

更新:

此外,null如果符合条件,您可以退货:

myFunc():myFuncResult {
    if (something) 
       return { abc:'abc' } //ok here

    return null;
}

可以在这里看到一个工作示例

于 2020-03-11T07:10:04.387 回答