Skip to content

Type unexpectedly not narrowed after checkΒ #58032

@frankdejonge

Description

@frankdejonge

πŸ”Ž Search Terms

Type narrowing, type narrowing with conditionals, type not narrowed after check

πŸ•— Version & Regression Information

This is the behavior in every version I tried, and I reviewed the FAQ for entries about type narrowing

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.5.0-dev.20240402#code/C4TwDgpgBAsghiARhAEnAzgSQHYDMD2ATgLZzACW+2UAvFAN4BQULUEp5ANgPwBcU6YIXLYA5gBpmrbHGIQ+DKa1a5yhQQsHCxk5cs4ZgmoSIlKoAX0ZXGoSFDToAoh04BBbABNMuTMEcAcrIQfo4AYmqCQXK0isrscFz8Wqa60sEKTHoqkcDJJjrm+obG2mbKVja4AK7YAMYUVFBCcNjoBCQAFLiE+MT88EioGDgdpI3YAJT8ji6J7l4+oRjRIf4YEerAq3GsdVSCbK6xPX0AdAlcANyM5uS4UJ2XnLQ0dLWeEKrYEJ6Tu9lgAALXoAdygP3BTkIvUInQA5AEAPIABSc8MmNwqt2UhAgwGqhGop2IZxkcm4Z1UWyKrG4DGe4ghwX4JLJwSs2RY-HozwsNwsQA

πŸ’» Code

type MaybeHasInformation = {
    email?: string,
    name?: {
        first?: string,
        last?: string,
    }
}

type HasEmailAndIfItHasNameItHasFirstName = {
    email: string,
    name?: {
        first: string,
        last?: string,
    }
}

function transform(from: MaybeHasInformation): HasEmailAndIfItHasNameItHasFirstName {
    const email = from.email;

    if (email === undefined) {
        throw new Error('NOPE');
    }

    return from.name?.first
        ? {email, name: from.name}
        : {email};
}```


### πŸ™ Actual behavior

There is a compilation error:

Type '{ email: string; name: { first?: string | undefined; last?: string | undefined; }; } | { email: string; }' is not assignable to type 'HasEmailAndIfItHasNameItHasFirstName'.
Type '{ email: string; name: { first?: string | undefined; last?: string | undefined; }; }' is not assignable to type 'HasEmailAndIfItHasNameItHasFirstName'.
The types of 'name.first' are incompatible between these types.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.


### πŸ™‚ Expected behavior

No error was expected.

### Additional information about the issue

_No response_

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions