Skip to content

Types not flowing down as expected to sort #5414

@johnnyreilly

Description

@johnnyreilly

I think I've encountered a problem with types flowing down correctly. Take the following code:

function stringComparer<T>(propLambda: (item: T) => string) {
  return (obj1: T, obj2: T) => {
    const obj1Val = propLambda(obj1) || '';
    const obj2Val = propLambda(obj2) || '';
    return obj1Val.localeCompare(obj2Val);
  };
}

var myBooks = [
    {title: 'Sherlock Holmes'},
    {title: 'Moby Dick'}
];

myBooks.sort(stringComparer(x => x.title));

console.log(myBooks);

The stringComparer allows us to sort an array, given a string lambda expression. In this case I'm looking to sort my array of books by their title.

However, even though sort is expecting compareFn?: (a: T, b: T) => number and stringComparer delivers on that with (obj1:T, obj2: T) => number there is a problem. The type of x in x => x.title has not flowed though as expected. It is not {title: string}. It's just {}.

You can see this in the playground here

I'm not certain if this is a but or if I've missed a trick here - I thought I'd best report it just in case.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions