Suddenly from today, the code below started to occur ts2322 error.
This works well in Typescript playground
I can't find anything wrong with it, but what's the problem?
I'm using Visual Studio Code 1.56.2
class Klass {
value?: number;
constructor(value?: number) {
this.value = value;
}
}

You haven't mentioned this, but I assume you're using the nightly builds published in npm as typescript@next. If so, you are likely seeing a preview of a new feature for TypeScript 4.4, "strict optional properties", as implemented in microsoft/TypeScript#43947. (UPDATE 2021-06-10) This functionality was originally going to be enabled via a new --strictOptionalProperties compiler flag, which would have been included in the --strict suite of compiler options. However, according to this comment, the flag will be renamed and removed from --strict, so anyone who wants to see this behavior in TypeScript 4.4 and above will need to manually enable it, via some compiler flag whose name has not yet been decided.
Strict optional properties will prevent you from assigning undefined to an optional property, while still allowing you to read undefined from such a property. This is more in keeping with how people have wanted optional properties to be for a long time, as evidenced by the (now finally closed) issue microsoft/TypeScript#13195.
Anyway, this means it is no longer safe to assign a value read from an optional parameter into an optional property of the same type, without first checking if it is undefined:
class Klass {
value?: number;
constructor(value?: number) {
if (value !== undefined) this.value = value;
}
}
Playground link to code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With