打字稿函数在界面中返回不同类型的结果

myFuncResult interface {

  abc: string

}


function myFunc():myFuncResult {

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


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

}

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


一只斗牛犬
浏览 83回答 2
2回答

慕运维8079593

既然您要返回两种不同的类型/接口(可以是字符串,也可以是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';}

狐的传说

发生这种情况是因为string不等于接口类型myFuncResult。myFuncResult您可以使用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;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript