Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conditional return types don't work #46127

Closed
kwasimensah opened this issue Sep 29, 2021 · 3 comments
Closed

Conditional return types don't work #46127

kwasimensah opened this issue Sep 29, 2021 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@kwasimensah
Copy link

Bug Report

πŸ”Ž Search Terms

conditional return type alias generics

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about conditional return types

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

type Test<T> = T extends string ? number : boolean;

function foo<T>(x: T): Test<T>{
  if(typeof x === "string"){
    return 5;
  }
  return true;
}

πŸ™ Actual behavior

Both branches have different flavors of error 2322

πŸ™‚ Expected behavior

the typeof guard should have let Typescript know it was dealing with a string and should have now which branch of the conditional type it should be allowed to return. The same outside of the type guard since it returns and control flow analysis should have treated that like an implicit else.

@kwasimensah
Copy link
Author

kwasimensah commented Sep 29, 2021

What I'm really trying to do:

I'm trying to write a function that when giving a string returns Wrapped<string> but if the type is already wrapped passes it through.

The closest I got this to working is with overloads but then I couldn't get it working with downstream functions even if they had overloads. https://www.typescriptlang.org/play?ts=4.4.3#code/JYOwLgpgTgZghgYwgAgOpTgB0xAJgHgBUA+ZAbwChlkoI5cB7EAGwE9kxWcAuZAIgDuGbHj4BuKjTqMW7AG5xmAVwi9CEgL4VtMJSARhgTZAiZzoYABQAPXgGcwUUAHMAlMl7osOAg6chnYgldfUNjUxBzKDAiYhtPYR9Y9wTvPFjgvQMjEBMzC3jkPQBrEAYBEBSikFLy3MpqamAYS04cBhhka2QAXj7+Pxc+VwbGsdowJSh6ttV+ITTcPgAaZAVlOesNCTGtcYhJ6a6KLR0ssNycKABbYDs7YHMAMXOc2MLBgOQAHzRE9JKZQqxCqXhEBEBdVIowmU1yESiVmsrk02jRQA

So I tried to be smart about doing the conditional in the return type and saw this bug.

@jcalz
Copy link
Contributor

jcalz commented Sep 29, 2021

duplicate of #33912

@andrewbranch andrewbranch added the Duplicate An existing issue was already created label Oct 1, 2021
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants