Skip to content

Contextual type inference breaks on function parameters with explicit return #53954

Closed
@evankim390

Description

@evankim390

Bug Report

πŸ”Ž Search Terms

contextual type inference function return generic

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about generics.

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

interface Options<K> {
    key: K;
    fn(key: K): any;
}

function id<K>(options: () => Options<K>) {
    throw 'unimplemented';
}

const breaks = id(() => {
    return {
        key: { id: 32 },
        fn(key) {
            // 'key' is of type 'unknown'.(18046)
            return key.id.toString();
        },
    };
});

const works = id(() => ({
    key: { id: 32 },
    fn(key) {
        return key.id.toString();
    },
}));

πŸ™ Actual behavior

The fn parameter type is only correctly inferred in the case where an arrow function is directly returning an object.

πŸ™‚ Expected behavior

I would expect for both cases to be handled consistently.

Activity

RyanCavanaugh

RyanCavanaugh commented on Apr 21, 2023

@RyanCavanaugh
Member

Duplicate #47599

jcalz

jcalz commented on Apr 21, 2023

@jcalz
Contributor

@RyanCavanaugh Is a block body context sensitive in a way that a concise body isn’t? I suspect as much but I’d love to hear official word since #47599 doesn’t seem to talk about that specifically.

ahejlsberg

ahejlsberg commented on Apr 22, 2023

@ahejlsberg
Member

This isn't related to #47599. Rather, it's an issue that was already fixed in #50903. The example works as expected in 5.1.

ahejlsberg

ahejlsberg commented on Apr 22, 2023

@ahejlsberg
Member

So, I'll call this a duplicate of #50687.

typescript-bot

typescript-bot commented on Apr 24, 2023

@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

        @jcalz@evankim390@ahejlsberg@RyanCavanaugh@typescript-bot

        Issue actions

          Contextual type inference breaks on function parameters with explicit return Β· Issue #53954 Β· microsoft/TypeScript