TS2412: exactOptionalPropertyTypes property assignment - in CI
With exactOptionalPropertyTypes on, directly assigning undefined to an optional property fails unless the property type includes undefined.
What this error means
Type-checking fails with TS2412 at a property assignment that sets an optional field to undefined.
tsc
src/config.ts(9,3): error TS2412: Type 'undefined' is not assignable to type 'string' with 'exactOptionalPropertyTypes: true'.Common causes
How to fix it
Include undefined in the property type
- Declare the optional property as type | undefined where appropriate
ts
interface Config { region?: string | undefined }Skip the assignment when there is no value
- Conditionally assign only when a value exists, leaving the key absent otherwise
ts
if (region) config.region = regionHow to prevent it
- Treat optional and undefinable as distinct under exactOptionalPropertyTypes and only assign present values.
Frequently asked questions
What causes "TS2412 exactOptional property"?
Type-checking fails with TS2412 at a property assignment that sets an optional field to undefined.
How do I fix TS2412 exactOptional property?
Include undefined in the property type
Related guides
TS2375: exactOptionalPropertyTypes undefined mismatch - in CIFix "error TS2375: Type ... not assignable with exactOptionalPropertyTypes: true. Consider adding undefined t…
TS2322: Type is not assignable - in CIFix "error TS2322: Type 'X' is not assignable to type 'Y'" when tsc runs in CI - a genuine type mismatch on a…
TS2564: Property has no initializer - in CIFix "error TS2564: Property 'x' has no initializer and is not definitely assigned in the constructor" under s…