-
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
Incorrect error of use of unassigned variable #13811
Comments
a has the type of {}, and has no value assigned.
so what you wanted:
|
@devdoomari It is not what I want. Full code: let a: {};
for (const x of y) {
if(x.q) {
a =x.q;
break;
}
}
// Assign default value if couldn't assign before
if (!a) {
a = {};
} |
The control flow checker (in strict null checks mode) assures that you'll never accidentally observe let a: {} | undefined; The problem with your suggestion is that we'd no longer catch this: let a: string;
// Intended to have assignment here, but forgot
if (!a) {
// Think I have an empty string, but I have undefined
} |
@ahejlsberg What about this case ? I would expect it compiling fine since I am checking against undefined. let a: number;
if (typeof a !== "undefined") {
a = 1;
} |
I think the same argument holds. If the declared type of a variable does not include |
That's what I ended with. |
@ahejlsberg I feel more safe using this helper now. function isNullOrUndefined<T>(obj: T | null | undefined): obj is null | undefined {
return typeof obj === "undefined" || obj === null;
}
if (!isNullOrUndefined(a)) { ... } But prefer to have something in the language like: iff (a) { ... } |
Adding entirely new statements beyond what JavaScript has is definitely out of scope for TypeScript. To check if a value is |
Thanks. |
TypeScript Version: 2.1.5
strictNullChecks: true
Code
Expected behavior:
Code compiles fine.
Actual behavior:
Use of unassigned variable.
The text was updated successfully, but these errors were encountered: