Home > Net >  How to declare typescript type to guarantee it's an assignable subset of another type
How to declare typescript type to guarantee it's an assignable subset of another type

Time:11-17

I'm trying to declare a merge function that will assign all the fields of one value to another value but I'm having trouble properly defining the types of the merge function. I can never get all the test case to pass.

interface Person {
  Name: string;
  Age: number;
  Occupation?: string;
}

// Tried
const merge = <T>(full: T, partial: Partial<T>): T => ({ ...full, ...partial });

// Also Tried
const merge = <T, U>(full: T extends U, partial: U): T => ({ ...full, ...partial });

const human: Person = {
  Name: "John",
  Age: 35,
};

// Expected results:
merge(human, { Age: 5 });                  // ✓
merge(human, { Name: "Marc" });            // ✓
merge(human, { Name: undefined });         //            
  • Related