'TypeScript is ignoring generic type when combining optional one

I have a problem with typing generic function and I narrowed my problem to this:

When combining generic type A with any regular object B TypeScript completely ignores generic one and treats it as B.

interface RegularObjType {
  regularKey: string;
}

interface BaseObjType {
  baseKey: string;
}

function addBasePropertyToObject<T extends { [key: string]: any }>(
  genericObj?: T,
  regularObj?: RegularObjType
) {
  const baseObject: BaseObjType | undefined = { baseKey: "baseValue" };

  const baseWithRegular = {
    ...baseObject,
    ...regularObj
  };

  const baseWithGeneric = {
    ...baseObject,
    ...genericObj
  };

  return { baseWithRegular, baseWithGeneric };
}

const {baseWithGeneric, baseWithRegular} = addBasePropertyToObject(
  { genericKey: "genericValue" },
  { regularKey: "regularValue" }
);

Assumed types by TypeScript:

// baseWithRegular type is combination of both
const baseWithRandom: {
  randomKey?: string | undefined;
  baseKey: string;
}

// baseWithGeneric type is just baseObject
const baseWithGeneric: {
  baseKey: string;
}

Because of that I don't have the access to keys of generic I passed to the function.


//                       👇 Works
const {baseKey: baseKey1, regularKey} = baseWithRegular
//                       👇 Property 'genericKey' does not exist on type '{ baseKey: string; }'.
const {baseKey: baseKey2, genericKey} = baseWithGeneric

Is there a way of getting better typing in this particular case?

Code sandbox link: https://codesandbox.io/s/gracious-stallman-bbr2ek?file=/src/index.ts



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source