Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use Typescript object spread operator to add optional properties?

I’m trying to add a property to an object, only if it has been defined:

const b = true;
const a = { ...(b !== undefined ? { b }: null  ) };

I was expecting the type of a to be:

const a: {
    b?: boolean;
}

Instead, the type of a is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const a: {
    b?: boolean | undefined;
}

Using TypeScript 4.8.2

>Solution :

If you want this behavior you will need to enable exactOptionalPropertyTypes in your compiler options:

const b = true;
const a = { ...(b !== undefined ? { b }: null  ) };
//   ^? { b?: boolean }

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading