Let's focus on analyzing the following code snippet:
class Bar {
kind: "bar"
constructor(public id: number) {}
}
If we set the compiler option strictNullChecks
to false
, then declaring kind: "bar"
implicitly allows assigning values of undefined
and null
to the kind
property. It becomes clear that initializing the field with a value other than undefined
is crucial in this scenario.
Now, let's proceed with strictNullChecks
enabled (set to true
). In this case, only the value "bar"
can be assigned to the kind
property. It seems like you are expecting the compiler to deduce the following logic:
The declaration kind: "bar"
specifies that the field named kind
must have type "bar"
. Therefore, only the value "bar"
should be assigned to it. Thus, I should automatically initialize it with "bar"
since no other value is valid.
The issue arises with TypeScript 2.x, even when using
strictNullChecks</code, fields can initially have the value <code>undefined
despite not allowing direct assignment of
undefined
. To clarify: while you cannot directly assign
undefined
to
kind
, the field can start with the value
undefined
if left uninitialized without triggering an error. This behavior has sparked conversations within the TypeScript community as some view it as a flaw in the language design. You can refer to the related
issue report.
Ultimately, the compiler does not perform the expected reasoning mentioned above. Therefore, currently, you will need to redundantly specify the string literal type and explicitly initialize your kind
properties.