Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

95
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda