-
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
Enforce definite initialization of static
members
#27899
Comments
Is the suggestion that we should always error on a static field with no initializer? |
@andy-ms Would it be possible to error when I use a static field that hasn't been definitely assigned? Or, if this isn't a common enough pattern to support, then your suggestion is spot on. Either one feels safer than the current behavior to me. Eg. class A {
static s: number
}
if (x) {
A.s = 3
// OK to read A.s in this branch
}
// NOT OK to read A.s in this branch |
Related stackoverflow question I can't think of a decent workaround either. Any ideas? |
Why were |
Same rules as for non-static members should apply - if the type does not allow @weswigham What kind of feedback do you await? I just discovered a very dumb bug that would have been caught by this check: export class JSONPreprocessorType implements MessagePreprocessorType {
static contentType: 'application/json';
} (It should have been an |
I would prefer to have the error early on - at the site of the declaration. Usually you can't figure out the usage anyway (since it's in another file). I recently had the same problem as @Yogu, and was thoroughly surprised by |
static
members
I just ran into this bug following a type ( |
Since class static blocks were introduced in 4.4, it seems like TS can use the same heuristic that's used for instance variables and constructors: class Foo {
// Suggested error: Property 'instanceValue' has no initializer and is not definitely assigned in a static block.
static staticValue: number;
// @ts-expect-error "Property 'instanceValue' has no initializer and is not definitely assigned in the constructor.(2564)"
instanceValue: number;
static {
// this.staticValue = 42;
}
constructor() {
// this.instanceValue = 42;
}
} |
I am facing a similar issue: export class SelfData {
private static _instance: SelfData;
public static get Instance(): SelfData {
if (this._instance === null) {
this._instance = new SelfData();
}
return this._instance;
}
} Here |
@weswigham I have also provided a feedback. Would you like to look into this issue again? |
Is there some clever reason why TSC can't check this (maybe... related to semantics of JS inheritance?)?
TypeScript Version: 3.2.0-dev.20181011
Search Terms: strictPropertyInitialization, static, initialized, uninitialized, assigned, property
Code
Expected behavior: Both lines should produce compile errors.
Actual behavior: Both lines result in runtime exceptions.
Playground Link
Related Issues:
The text was updated successfully, but these errors were encountered: