Home > Blockchain >  Property 'firstName' does not exist on type 'object'
Property 'firstName' does not exist on type 'object'

Time:04-26

function marge(obj1: object, obj2: object) {
    return Object.assign(obj1, obj2);
}

const margeObj = marge( {firstName: "John"}, {lastName : "Doe"} );
console.log(margeObj.firstName);

Typescipt throwing error at last line while trying to get property firstName of mergeObj.

Property 'firstName' does not exist on type 'object'.

Both obj1 and obj2 are object and adding return type object does not fixed this problem.

CodePudding user response:

TypeScript doesn't understand what type the merge function should return. You can specify the arguments with generics and then merge them in the return type with the & intersection operator:

function marge<T extends {}, S extends {}>(obj1: T, obj2: S): T & S {
    return Object.assign(obj1, obj2);
}

const margeObj = marge({firstName: "John"}, {lastName: "Doe"});
console.log(margeObj.firstName);

The returned type will be the intersection between T and S, all properties in the object arguments will be available in the return type.

X extends {} simply constrains the argument to an object.

CodePudding user response:

I think you've to use an interface like this.

function marge(obj1: object, obj2: object) {
    return Object.assign(obj1, obj2);
}
interface user {
    firstName:string;
    lastName:string;
}
const margeObj:user = marge( {firstName: "John"}, {lastName : "Doe"} );
console.log(margeObj.firstName);

CodePudding user response:

One solution is to use existential quantification, like:

function marge<T, U>(obj1: T, obj2: U): T & U {
  return Object.assign(obj1, obj2);
}

This says, for the params obj1 and obj2 there exists some types, T and U, respectively. The function doesn't know what those types are, but it does know it should return an intersection type from them.

  • Related