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
class A {
static s: number
a() {
A.s * 3 // Should be a compile error
}
}
A.s * 7 // Should be an compile error
Expected behavior: Both lines should produce compile errors.
Actual behavior: Both lines result in runtime exceptions.
Related Issues:
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 static properties specifically excluded from --strictPropertyInitialization?
Is the suggestion that we should always error on a static field with no initializer?
Same rules as for non-static members should apply - if the type does not allow undefined, the property needs to be initialized, otherwise it would have a value that's not allowed.
@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 = instead of :.)
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 strictNullChecks not catching this problem.
Most helpful comment
Is the suggestion that we should always error on a static field with no initializer?