简体   繁体   English

类型“object”上不存在属性“firstName”

[英]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.尝试获取 mergeObj 的属性 firstName 时,Typescipt 在最后一行抛出错误。

Property 'firstName' does not exist on type 'object'.类型“object”上不存在属性“firstName”。

Both obj1 and obj2 are object and adding return type object does not fixed this problem. obj1 和 obj2 都是 object 并且添加返回类型 object 没有解决这个问题。

TypeScript doesn't understand what type the merge function should return. TypeScript 不明白合并 function 应该返回什么类型。 You can specify the arguments with generics and then merge them in the return type with the & intersection operator:您可以将 arguments 指定为 generics,然后使用&交集运算符将它们合并到返回类型中:

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.返回类型将是TS之间的交集, object arguments 中的所有属性都将在返回类型中可用。

X extends {} simply constrains the argument to an object. X extends {}只是将参数限制为 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.这表示,对于参数obj1obj2 ,分别存在一些类型TU The function doesn't know what those types are, but it does know it should return an intersection type from them. function 不知道这些类型是什么,但它知道它应该从它们返回一个交集类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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