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

null coalescing operator doesn't narrow types in some complex circumstances involving generics #49191

Closed
Zachiah opened this issue May 20, 2022 · 0 comments · Fixed by #49119
Closed
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue

Comments

@Zachiah
Copy link

Zachiah commented May 20, 2022

Bug Report

🔎 Search Terms

Null Coalescing operator:
I found this issue which is very similar, but I don't think it's the same. I mean it seems to me that if the compiler can correctly narrow the type with the ternary it should do the same for the null coalescing

🕗 Version & Regression Information

  • I have determined that in v4.2.3 all 3 examples from my code fail, and that in v4.3.5 only the last fails. I think none of them should fail, but I'm not positive on that, only positive that they all should behave the same

⏯ Playground Link

Playground Link

💻 Code

type TagName = "div" | "span" | "li" | "ul" | "ol";

export type ForwardingProps<T extends TagName, Default extends TagName> = Default extends T ? {
  as?: T;
  ref: HTMLElementTagNameMap[T]
} : {
  as: T;
  ref: HTMLElementTagNameMap[T]
}

const fn = <T extends TagName = "li">(p: ForwardingProps<T, "li">) => { }


const fn2 = <T extends TagName = "span">(p: ForwardingProps<T, "span">) => {
  const {as = "span"} = p;
  const as2 = p.as ? p.as : "span";
  const as3 = p.as ?? "span";

  fn({
    as: as,
    ref: p.ref
  });

  fn({
    as: as2,
    ref: p.ref
  })

  fn({
    as: as3,
    ref: p.ref
  })
}

🙁 Actual behavior

Typescript happily understands the first 2 attempts at removing null from the possible types (object destructuring defaults and the ternary operator) but complains when the null coalescing operator is used.

🙂 Expected behavior

The null coalescing operator should behave exactly the same as the equivalent ternary or object destructuring expression

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants