Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

257
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda