-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Object narrawing to function broken on v3.1 #27969
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
Comments
The problem is that all functions are assignable to type FunctionsMustReturnString<T> = T extends Function ? () => string : T;
function stringify<T>(x: FunctionsMustReturnString<T>): string {
if (typeof x === 'function') {
return x();
}
return String(x);
}
stringify(2); // OK
stringify(() => ""); // OK
stringify(() => 2); // Error
stringify((p: string) => p); // Error |
Thank you for the response, I will certainly update my code as you have suggested. I guess I should consider this bug in v3.0, rather then a regression in v3.1. |
Also some discussion of a similar pattern in #27278 |
Related? #26970 |
Something that seems inconsistent is that the following does NOT throw an error in 3.2.0-dev.20181018: function stringify<T = {} | (() => string)>(x: T): string {
if (typeof x === 'function') {
return x();
}
return String(x);
} Which seems equivalent to the original erroneous code? |
When you write |
That makes perfect sense... thanks again! |
TypeScript Version: 3.2.0-dev.20181018
Search Terms: function narrowing guard
Code
Expected behavior: The example code should compile without error.
Actual behavior: Compiler error: "Cannot invoke an expression whose type lacks a call signature. Type 'Function | (() => string)' has no compatible call signatures."
Playground Link: http://www.typescriptlang.org/play/#src=%2F%2F%20Error%20in%203.2.0-dev.20181018%2C%20but%20works%20in%20v3.0.1!%0D%0Afunction%20stringify(x%3A%20%7B%7D%20%7C%20(()%20%3D%3E%20string))%3A%20string%20%7B%0D%0A%20%20%20%20if%20(typeof%20x%20%3D%3D%3D%20'function')%20%7B%0D%0A%20%20%20%20%20%20%20return%20x()%3B%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20return%20String(x)%3B%0D%0A%7D%0D%0A
Related Issues: None that I could find.
The text was updated successfully, but these errors were encountered: