简体   繁体   中英

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

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.

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.

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM