How to make type of conditional object property to not be undefined

Viewed 34

I have the following object which has a conditional property on it

function someCondition() {
  return Math.random() > .5 ? true : false
}

const DICTIONARY = {
  propertyA: 'propertyA' as const,
  ...(someCondition() && {
    propertyB: 'propertyB' as const,
  }),
};

The intent here is to have an object where the propertyB may or may not exist on it, but if it does it should only have the type of propertyB, which in TS would be expressed as

{
    propertyB?: "propertyB";
    propertyA: "propertyA";
}

However the inferred type is actually

{
    propertyB?: "propertyB" | undefined;
    propertyA: "propertyA";
}

which is not the intent of the above code. propertyB should either exist or not exist (?:) and if it exists it should only be propertyB and not also undefined

I have tried to strictly define the type of DICTIONARY by hand, but it always ends up with the wrong type.

How can I narrow it down to just an optional property which cannot be undefined?

TS playground link

0 Answers
Related