myFuncResult interface {
abc: string
}
function myFunc():myFuncResult {
if(something) return { abc:'abc' } //ok here
return 'result' //but this line gave me warning
}
我有两种基于条件的结果类型(对象和字符串),如何在我的界面中声明它?
myFuncResult interface {
abc: string
}
function myFunc():myFuncResult {
if(something) return { abc:'abc' } //ok here
return 'result' //but this line gave me warning
}
我有两种基于条件的结果类型(对象和字符串),如何在我的界面中声明它?
既然您要返回两种不同的类型/接口(可以是字符串,也可以是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;
}