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

252
Views
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 answers
Answer question

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 Report
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!