-
Notifications
You must be signed in to change notification settings - Fork 12.5k
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
Generalize never
type handling for control flow analysis based type guard
#12825
Comments
It would be a great way to control the flow. For now, you may use function throwError(): never {
throw new Error();
}
let foo: string | undefined;
if (!foo) {
throwError();
return:
}
foo; // foo is string or use a check typeguard function throwError(): never {
throw new Error();
}
// Inferred return type is T
function check<T>(x: T | undefined) {
return x || throwError();
}
let foo: string | undefined;
let foosafe = check(foo); // foosafe is string |
Related: #8655 |
I'd like to echo my support for this. Currently to get control flow analysis to work correctly in our codebase (which make use of a framework requiring the use of an external throwError style method), we explicitly ADDENDUM: I've just noted RyanCavanaugh's comment on a duplicate thread.
We'll use this workaround from now on. It appears to not interfere with the returned type. 👍 if (!foo) {
return throwError();
} |
I currently use |
@masaeedu In that way you strip away not only |
@parzh Depends on what your value's type is. If the type is |
I got |
For other people googling this, this issue was addressed in #14490. Basically it seems the issue is TS currently has separate passes for flow control and type assignment, and the former needs to run first for the latter to work, and there didn't seem to be any clean solutions that would also handle imported functions, etc.... |
The workaround doesn't work in top-level code outside functions, since there's no |
@Kinrany you can still use the other workaround |
The original code in this issue has been working as expected for a while. Is there anything else above that isn't right? I'm thinking no, and that this issue can be closed. |
I guess there would be some duplicates, but I cannot find it.
TypeScript Version: 2.1.14
Code
The text was updated successfully, but these errors were encountered: