Skip to content

typescript throws error when you want to initialize an arrow function that returns different objects based on overloaded string literal union typeΒ #55606

Closed as not planned
@reza-ss

Description

@reza-ss

πŸ”Ž Search Terms

arrow function
union
overload

πŸ•— Version & Regression Information

all TS versions

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.2.2#code/PTAEDsHsCcFsEMA2oBmBXcBjALgS0uKJAG4Cm0ik8AJqAO4wDWAzvaYogIQBQ36WeAqGylm2ABTEAXACIAFu0oyAlFIDeCjpCng0sAEbkAvgG4+GHPkIixk2XNwr1DqfsiREpeOFO9zAq2FRbFA7UDFoXHAAc2U1blBQXBRJUABeDNB5RUgVeMTE6FJsNGhCDRypAEYAJgBmX0SjdmZSUCKSstANXClsaDRSI25hkHbi0vAAFQBPAAc23FZMGCKcTjMbCWytFTNuMew5aEg6VnIT6CTCeGgTulQLQXAebmx5tpJyShp07oSCnYdkpVBUtDo9IZoI1AdJ5I5QS43B4vD4zE0AQCVuAxEExDUpF8KFRaGlQsRlGkAHz5JIpYjpTLA3JxAGFCZdMGUar1GHNRCtcadcoufqDYYYg5gDqTWYLJLLVakdbovHYGriZl7IA

πŸ’» Code

// normal function overload works well!

function test(v:"hello"):{hello:number};
function test(v:"hi"):{hi:boolean};


function test (v: string){
  if(v === "hello"){
    return {hello:123};
  }else return {hi:true}
}
// returnType is correct!;
test("hello");

// throws error in arrow function!

type overload = {
    (v:"hello"):{hello:number};
    (v:"hi"):{hi:boolean};
  }
  
  const test2:overload = (v)=>{
  if(v === "hello"){
    return {hello:123};
  }else return {hi:true}
  }

// returnType is correct!;
  test2("hello");

πŸ™ Actual behavior

typescript throws error when you want to initialize an arrow function that returns different objects based on overloaded string literal union type.

πŸ™‚ Expected behavior

TS most not throws error in this case as it does not throws error in normal function

Additional information about the issue

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions