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

Narrowing return type inside a generic function using object map #53952

Closed
alesmenzel opened this issue Apr 21, 2023 · 2 comments
Closed

Narrowing return type inside a generic function using object map #53952

alesmenzel opened this issue Apr 21, 2023 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@alesmenzel
Copy link

Bug Report

Incorrectly narrowing type inside a generic function where the return type is indexed from an object.

🔎 Search Terms

Generics, Mapped types, index types

🕗 Version & Regression Information

  • This is a crash No
  • This changed between versions - on version 3.3.3333 did not error, but was not correct type either
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about generics, index types

⏯ Playground Link

Playground link with relevant code

💻 Code

type A = {
    a: number
}

type B = {
    b?: string
}

type MAP = {
    a: A,
    b: B
}

function getProfilesForNetwork<Network extends keyof MAP>(network: Network): MAP[Network] {
    if (network === 'a') {
        return { a: 43 }
    }
    if (network === 'b') {
        return { b: 'bbbbb' }
        // ERROR - Property 'a' is missing in type '{ b: string; }' but required in type 'A'.(2322)
        // Network is generic over 'a' | 'b' so it can be only 1 of those values, the value should narrow the return type to B here
    }
    throw new Error('Unknown!')
}

🙁 Actual behavior

TS expects the return type to be A & B.

🙂 Expected behavior

The network === 'a' / network === 'b' should narrow the return type and should be either A or B.

@RyanCavanaugh
Copy link
Member

This isn't doing what you think it's doing; there isn't narrowing on type parameters like the code sample implies:

function getProfilesForNetwork<Network extends keyof MAP>(network: Network): MAP[Network] {
    if (network === 'a') {
        return { a: 43 }
    }
    if (network === 'b') {
        return { a: 32 } // <- no error
    }
    throw new Error('Unknown!')
}

See #33014

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Apr 21, 2023
@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

3 participants