Typescript重载

huangapple go评论65阅读模式
英文:

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 {

TypeScript Playground.

英文:

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 {

TypeScript Playground.

huangapple
  • 本文由 发表于 2023年7月3日 04:39:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76600702.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定