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

Cannot type-guard conditional extends WeakRef #45626

Closed
jhunterkohler opened this issue Aug 29, 2021 · 2 comments
Closed

Cannot type-guard conditional extends WeakRef #45626

jhunterkohler opened this issue Aug 29, 2021 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@jhunterkohler
Copy link

jhunterkohler commented Aug 29, 2021

Bug Report

🔎 Search Terms

  • WeakRef
  • weakreference
  • conditional
  • conditional type
  • conditional not assignable
  • return type not assignable
  • conditional typeguard
  • instanceof
  • instanceof typeguard
  • instanceof extends

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about:
    • Generics
    • Typeguards

⏯ Playground Link

Playground link with relevant code

💻 Code

/**
 * If `value` is a `WeakRef`, return the dereferenced object, or throw if
 * it has been garbage collected. Else, return `value`. */
function xderef<T>(value: T): T extends WeakRef<infer U> ? U : T {
    if (value instanceof WeakRef) {
        const val = value.deref();

        if (!val) {
            throw new ReferenceError(value);
        }

        return val;
    }

    return value;
}

🙁 Actual behavior

Compiler reports, on the final return statement return value:

Type 'T' is not assignable to type 'T extends WeakRef ? U : T'.

🙂 Expected behavior

Compiler would recognize that T does not extend WeakRef, thus that T must only be compatible with itself.

@jcalz
Copy link
Contributor

jcalz commented Aug 30, 2021

duplicate of #33912

@andrewbranch andrewbranch added the Duplicate An existing issue was already created label Sep 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