Home > Software design >  How to use Typescript object spread operator to add optional properties?
How to use Typescript object spread operator to add optional properties?

Time:08-31

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:

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

Using TypeScript 4.8.2

CodePudding user response:

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

  • Related