Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

94
Views
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

about 4 years ago ยท Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!