Closed
Description
I recently upgraded from 2.2.1 to 2.3.1 version and suddnely I get a compiling error, which I wouldn't expect at all. Please see code example, and also you can see the error in Typescript playground, http://bit.ly/2rBt43G
TypeScript Version: 2.3.1 / "lib": ["es2015"]
Code
interface Person {
name: string;
age: number;
}
function doSomething(): string {
return 'something';
}
function doPromise(): Promise<Person> {
return new Promise(resolve => setTimeout(_ => resolve({ name: 'Fran', age: 38 }), 2000));
}
// No problem here
function doAsyncStuff(): Promise<string> {
return doPromise()
.then(_ => doSomething())
}
// No problem here
function doAsyncStuff2(): Promise<string> {
return doPromise()
.then(doSomething)
}
/**
* Compiler complains:
* Type 'Promise<Person>' is not assignable to type 'Promise<string>'
*/
function doAsyncStuff3(): Promise<string> {
return doPromise()
.then(doSomething.bind(null))
}
Expected behavior:
I would expect the compiler to infer the type of the function returned by "bind" function
Actual behavior:
It expects the type of the promise returned by "doPromise"
Thanks a lot
Metadata
Metadata
Assignees
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
jcalz commentedon Jun 21, 2017
This could be an instance of #212 and is hard to solve well without something like type operators over the tuples corresponding to parameter lists (as in #5453). As a workaround for your specific issue you could add a declaration like:
since you're not passing any initial arguments to the function being bound.
DanielRosenwasser commentedon Jun 21, 2017
I'm not sure why you're only seeing this in 2.3.1 - I guess we're not making correct inferences from the
onfulfilled
argument tothen
whenany
is passed in.In any case, there's definitely a limitation from #212. From both a performance type-safety perspective, you're better off using arrow functions instead of
bind
,call
, andapply
.jscriptcoder commentedon Jun 21, 2017
Thanks guys for the answer. Eventually I went for the arrow function as suggested by @DanielRosenwasser
typescript-bot commentedon Dec 5, 2017
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.