Skip to content

Bad type inference from return type #16099

Closed

Description

@dawidgarus

TypeScript Version: 2.2.1 / nightly (2.2.0-dev.201xxxxx)

Code

function flatMap<ItemType, ProjectedItemType>(projectorFn: (item: ItemType) => ProjectedItemType[]): (aggregate: ProjectedItemType[], item: ItemType) => ProjectedItemType[] {
	return (aggregate: ProjectedItemType[], current: ItemType) => aggregate.concat(projectorFn(current) || []);
}

['alice', 'bob'].reduce(flatMap(name => name.split('')), []);
['alice', 'bob'].reduce(flatMap<string, string>(name => name.split('')), []); // this works fine

Expected behavior:
TypeScript compiler should infer that type of name is string.

Actual behavior:
Compiler error: Property 'split' does not exist on type '{}'.

Activity

  1. ikatyang commented on May 26, 2017

    @ikatyang
    Contributor

    You have to provide some information for TS to infer types, otherwise it wouldn't know what name is.

    for example

    // <ItemType extends string>
    
    declare function flatMap<ItemType extends string, ProjectedItemType>(projectorFn: (item: ItemType) => ProjectedItemType[]): (aggregate: ProjectedItemType[], item: ItemType) => ProjectedItemType[];
    
    ['alice', 'bob'].reduce(flatMap(name => name.split('')), []);

    or

    // (name: string) => name.split('')
    
    declare function flatMap<ItemType, ProjectedItemType>(projectorFn: (item: ItemType) => ProjectedItemType[]): (aggregate: ProjectedItemType[], item: ItemType) => ProjectedItemType[];
    
    ['alice', 'bob'].reduce(flatMap((name: string) => name.split('')), []);
  2. dawidgarus commented on May 26, 2017

    @dawidgarus
    Author

    Ika (@ikatyang) I know, but it would be nice if compiler could work out type of name from return type.
    reduce expects (something[], string): something[] function and flatMap returns (ProjectedItemType[], ItemType): ProjectedItemType[]. When compiler doesn't know what is ItemType as assumes that it's {}, it could use that knowledge to infer that ItemType is string.

  3. ahejlsberg commented on May 26, 2017

    @ahejlsberg
    Member

    Duplicate of #15680. Fixed by #16072.

  4. mhegazy commented on Jun 9, 2017

    @mhegazy
    Contributor

    Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

  5. locked and limited conversation to collaborators on Jun 14, 2018
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

      Issue actions