Closed
Description
Strict property initialization checks in classes
- PR: Strict property initialization checks in classes #20075
- Every non-initialized property that does not have undefined in it type will be an error if not definitely assigned in the constructor, (meaning all code paths needs to have an initializer).
abstract
properties should be excludedT extends number | underfed
is an error, since we do not know if it is one or the other at instantiation time- Enabled under new strict mode flag
--strictPropertyInitialization
- Issues:
- names in quotes are not checked:
class B { a: number; // Error "b" : number; // No error }
- we do not do control flow analysis on
x["foo"]
currently, we only do it onx.foo
. - we could do that if we address Discriminant property type guard not applied with bracket notation #10530
- @sandersn did have a PR to address that, and the problem was perf
- also applies to symbols, or any computed property names
- we do not do control flow analysis on
- Do we need a new explicit modifier?
- How do you opt-out for a specific class
// @ts-ignore
- seems dangerous to rely on this, you change the type, and now no errors
- or put it in
"b"
- too cute..
- this looks like a bug that we should fix in the future
- new modifier:
- kotlin uses
lateinit
, swift haslazy
? - bang operator:
a!: number
- extend it to locals as well
- not allowed on
const
- should be an error to have it on something with an initializer
readonly
is ok to have!
to allow for external- does not amke sense for
static
s - @bterlson is not happy about
!
- but we have it in expression positions already
- not allowed on
- kotlin uses
- How do you opt-out for a specific class
- method calls in the constructor
- this guards against observing un-initialized properties outside the class, but not inside the class
- this allows for for init patterns
- it is also easy to get around this using aliases, or even through super access
- @DanielRosenwasser, all angular projects, mobx, etc.. that use decorators to initialize properties will have to opt-out of these features
- you can bang these properties
- it is possible that in the future to allow decorators to change the type of the declaration, and in that world we would not need to bang
- this is opt-in at the end of the day, and you can keep the world you are used to