英文:
Typescript overloding
问题
代码中的错误在于条件判断部分,您使用了&&
,但正确的逻辑运算符应该是&&
。以下是已更正的代码:
function position(): IPosition
function position(a: number): IPositionDefault
function position(a: number, b: number) :IPosition
function position(a?: number, b? :number){
if (!a && !b){
return {x: undefined, y: undefined}
}
if (a && !b){
return {x: a, y: undefined, default: a.toString()}
}
if (!a && b){
return {x: b, y: undefined, default: b.toString()}
}
return {x: a, y: b}
}
现在代码应该没有语法错误。
英文:
Guys where is an error in this code,
I suppose, I am covering all possible situations,
compiler saying I am wrong here - function position(a: number): IPositionDefault ,
but if there is one argument I returning object that looks like IPositionDefault, no?
function position(): IPosition
function position(a: number): IPositionDefault
function position(a: number, b: number) :IPosition
function position(a?: number, b? :number){
if (!a && !b){
return {x: undefined, y: undefined}
}
if (a && !b){
return {x: a, y: undefined, default: a.toString()}
}
if (!a && b){
return {x: b, y: undefined, default: b.toString()}
}
return {x: a, y: b}
}
I expected to see no error in compiler
答案1
得分: 1
To:
function position(a?: number, b?: number): IPosition | IPositionDefault {
英文:
All you need for error to go away to do is to define a return type of your actual function implementation.
Change:
function position(a?: number, b? :number){
To:
function position(a?: number, b? :number): IPosition | IPositionDefault {
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论