It seems like you're working with the nightly builds of TypeScript published on npm under typescript@next
. This might be giving you a sneak peek at a new feature in TypeScript 4.4 called "strict optional properties," which you can read more about here. (UPDATE 2021-06-10) Originally, this feature was going to be activated using the --strictOptionalProperties
compiler flag within the --strict
package of options. However, as mentioned in this comment, the flag will now have a different name and won't be part of --strict
, requiring manual activation through another yet-to-be-named compiler flag.
This update introduces stricter rules around optional properties, disallowing the assignment of undefined
to them but still permitting reading undefined
from such properties. This aligns better with user expectations for optional properties, as demonstrated by the resolution of the long-standing issue microsoft/TypeScript#13195.
Consequently, it's now essential to verify that a value obtained from an optional parameter is not undefined
before assigning it to an optional property of the same type, as illustrated below:
class Klass {
value?: number;
constructor(value?: number) {
if (value !== undefined) this.value = value;
}
}
Here's a helpful Playground link to code