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

247
Vistas
Hot to fix "Type 'undefined' is not assignable to type 'T[Extract<keyof T, string>]'"?
function copyFields<T>(target: T, source: Partial<T>): T {
    for (let id in source) {
        target[id] = source[id];  // Error
    }
    return target;
}

let x = { a: 1, b: 2, c: 3, d: 4 };

copyFields(x, { b: 10, d: 20 });

Code above occurs the error Type 'T[Extract<keyof T, string>] | undefined' is not assignable to type 'T[Extract<keyof T, string>]'. Type 'undefined' is not assignable to type 'T[Extract<keyof T, string>]'.

Doesn't source always a part of target?

What's the problem?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The type Type 'T[Extract<keyof T, string>] | undefined can be undefined, which cannot be assigned to type Type 'T[Extract<keyof T, string>].

Your input source may have a property that has been explicitly set to undefined, which would not be able to be assigned to the equivalent property on target.

You should check for this case, though it looks like this condition isn't enough for TypeScript to determine that it's definitely not undefined. However, you can then apply TypeScript's non-null assertion operator to make sure TypeScript realises this means the property is not undefined:

function copyFields<T>(target: T, source: Partial<T>): T {
    for (let id in source) {
        const sourceProp = source[id];
        if (typeof sourceProp !== 'undefined') {
          target[id] = sourceProp!;  // No error here
      }
    }
    return target;
}

let x = { a: 1, b: 2, c: 3, d: 4 };

copyFields(x, { b: 10, d: 20 });

TypeScript Playground

about 4 years ago · Juan Pablo Isaza Denunciar
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