-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
Primitive type guards require typeof
to be on the left hand side of the comparison
#9020
Comments
The error goes away for me after re-arranging the type guards in ...
if (typeof fn == "string") {
}
if (typeof fn != "function" || !type) {
return false;
}
... |
Note the following compiler behaviour (with typescript@next at least): function foo(x: string|number) {
if (typeof x === "string") {
x // x is narrowed to string here
}
if ("string" === typeof x) {
x // x is NOT narrowed here, still string|number
}
} Seems weird that the two equivalent forms are treated differently. But that's what it does at present. |
@mindplay-dk I think yours is a different problem - on the error line you linked to, the |
The spec provides only a few fixed forms for narrowing primitives. As a workaround, you can write a type predicate: function isString(x: any): x is string {
return "string" == typeof x;
}
// later...
if (isString(fn) || !type) {
return false;
} |
We discussed this offline and decided to change the spec in this case. |
typeof
to be on the left hand side of the comparison
@yortus why not? this works with 1.8.10, it only started failing with the nightly. |
@mindplay-dk control flow based type analysis (landed in #8010) has tightened up type guard type inference. You are right that it appears narrowing does cross function boundaries in v1.8, but the new behaviour is more accurate. The compiler does not know whether the function expression will be called immediately, or perhaps later, by which time The workaround is straightforward but a bit ugly - just introduce a new variable of the narrowed type inside the guarded block:
|
@yortus hmm, introducing an arbitrary variable as a work-around... stuff like that raises questions for someone reading it - like, if I were to see something like that, my immediate inclination would be to factor away a useless intermediary variable... ugly in deed :-/ |
@mindplay-dk yeah it's a smell, and it's not the only place you need to add a superfluous variable to make type inference happy. But in this case at least, I can't imagine how tsc could infer that it's safe to narrow inside the function expression without god-like knowledge of the runtime behaviour of the code. Maybe in your case it's cleaner to just use an explicit type assertion, i.e. |
@yortus thanks, a type assertion - yes, that's cleaner :-) |
Typecript method, the parameter does not support the function and the character of the joint type, prompt TS2345 error
The text was updated successfully, but these errors were encountered: