superstruct icon indicating copy to clipboard operation
superstruct copied to clipboard

`exactOptionalPropertyTypes: true` breaks type checking of optional values

Open IgnusG opened this issue 3 years ago • 4 comments
trafficstars

This tsconfig rule breaks typechecking of optional values since the following:

const mine = object({
  key: optional(string()),
});

creates the type as:

{
  key?: string | undefined
}

if we try assigning it to a value value typed as:

{
  key?: string
}

Typescript throws an error since that property is optional but not allowed to have undefined as a value. Semantically it makes more sense for optional() to follow this behaviour. However, this would be a breaking change and typescript itself ships this behind a flag so maybe this should not be the default behaviour, being instead behind a flag too?

IgnusG avatar Dec 10 '21 11:12 IgnusG

@IgnusG ah interesting. Do you know how we might make it a flag that is seamless? Otherwise we'd need to have people pass in a config each time they used optional?

ianstormtaylor avatar Mar 02 '22 16:03 ianstormtaylor

Hi @ianstormtaylor! Glad you're back 🙂

I got the idea to see if this cannot be checked programmatically by comparing the different types (something of a built-in flag) and sure enough seems like it can:

type A = {
  a?: boolean;
}

type B = {
  a?: boolean | undefined;
}

type C = undefined extends (A & B)["a"] ? "exactOptionalPropertyTypes off" : "exactOptionalPropertyTypes on";

With the exactOptionalPropertyTypes turned on type C here will be the latter string (as shown here). If we turn it off it will be the former string (example here).

Using this we could theoretically change the type returned by optional based on the user's typescript compiler settings in line with whichever option the user prefers to use. Let me know what you think of this solution.

IgnusG avatar Mar 07 '22 13:03 IgnusG

@IgnusG wow, that's really smart! I'd be open to that change.

ianstormtaylor avatar Jun 02 '22 13:06 ianstormtaylor

Hey @ianstormtaylor, would you consider a PR for this issue?

danroc avatar Sep 01 '23 07:09 danroc