Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Types not flowing down as expected to sort #5414

Closed
johnnyreilly opened this issue Oct 27, 2015 · 2 comments
Closed

Types not flowing down as expected to sort #5414

johnnyreilly opened this issue Oct 27, 2015 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@johnnyreilly
Copy link

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.

@RyanCavanaugh RyanCavanaugh added Effort: Difficult Good luck. Duplicate An existing issue was already created and removed Effort: Difficult Good luck. labels Oct 27, 2015
@RyanCavanaugh
Copy link
Member

Same root cause as #5256 -- contextual types do not flow through the return value of a function.

@johnnyreilly
Copy link
Author

Glad it's already been raised - thanks for responding @RyanCavanaugh.

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

2 participants