Skip to content

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

Closed
@Zachiah

Description

@Zachiah

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions