Skip to content

Indexed access type isn't taking information from conditional into account #44387

Closed
@sigurdschneider

Description

@sigurdschneider

Bug Report

🔎 Search Terms

index type, indexed access type, index access operator, extends, Exclude, conditional type

🕗 Version & Regression Information

This is the behavior in every version I tried (3.3.3 to 4.3.2), and I reviewed the FAQ for entries about indexed access types.

⏯ Playground Link

Playground link with relevant code

💻 Code

interface A {
    details1?: {y:string};
    details2?: {x:string};
}

function create<PropName extends keyof A>(
    name: PropName , a: A): Exclude<A[PropName], undefined> {
    const x: A[PropName] = a[name];
    if (x) return x; // Type error: Type 'A[PropName]' is not assignable to type 'Exclude<A[PropName], undefined>'.
    throw new Error();
}

🙁 Actual behavior

TypeScript complains that x in if (x) return x; is of type 'A[PropName]' and is not assignable to type 'Exclude<A[PropName], undefined>', because it assumes that x can be undefined.

🙂 Expected behavior

I would have expected that this works, as return x is the consequence of the conditional if (x), so x cannot be undefined.

Thanks for taking the time to look at this!

Activity

RyanCavanaugh

RyanCavanaugh commented on Jun 2, 2021

@RyanCavanaugh
Member

Duplicate #31908 & others. We'd need, at a minimum, #22348 to be able to model this correctly.

sigurdschneider

sigurdschneider commented on Jun 2, 2021

@sigurdschneider
Author

Too bad, thanks for taking a look.

typescript-bot

typescript-bot commented on Jun 4, 2021

@typescript-bot
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

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @RyanCavanaugh@sigurdschneider@typescript-bot

        Issue actions

          Indexed access type isn't taking information from conditional into account · Issue #44387 · microsoft/TypeScript