Home > Mobile >  Why does a union involving a conditionally defined property result in looser types than expected?
Why does a union involving a conditionally defined property result in looser types than expected?

Time:06-28

Consider the following TypeScript code:

const test = Math.random() < 0.5 ? { a: 1, b: 2 } : {};

I would expect the type of this object to be:

const test: {
  a: number;
  b: number;
} | {}

because this is the strictest type description of it. Either the conditional is true, in which case the object has two properties, or its not and the object has no properties.

Instead, I find the type to be

const test: {
  a: number;
  b: number;
} | {
  a?: undefined;
  b?: undefined;
}

This seems incorrect to me because there is no scenario in which properties can exist with undefined values.

Another example:

enter image description here

Here I've declared a type where the items property either does not exist on the object, or exists and is defined. I then inspect the generated type and see that the type has loosened such that items can exist as a property on the object and have a value of undefined.

What am I not understanding about TypeScript's typesafety guarantees?

CodePudding user response:

Typescript is by default slightly sloppy with optional properties. Specifically it doesn't distinguish properties that don't exist at all from those that are set to undefined. Set the option exactOptionalPropertyTypes in order to get the more precise type test: { a: number; b: number } | { a?: never; b?: never }.

  • Related