[英]error TS2345: Argument of type 'T' is not assignable to parameter of type 'object'
The code below was working fine with TypeScript 2.1.6: 下面的代码适用于TypeScript 2.1.6:
function create<T>(prototype: T, pojo: Object): T {
// ...
return Object.create(prototype, descriptors) as T;
}
After updating to TypeScript 2.2.1, I am getting the following error: 更新到TypeScript 2.2.1后,我收到以下错误:
error TS2345: Argument of type 'T' is not assignable to parameter of type 'object'. 错误TS2345:类型'T'的参数不能分配给'object'类型的参数。
Change signature of the function, so that generic type T
extends type object
, introduced in Typescript 2.2. 更改函数的签名,使泛型类型T
扩展类型object
,在Typescript 2.2中引入。 Use this syntax - <T extends object>
: 使用此语法 - <T extends object>
:
function create<T extends object>(prototype: T, pojo: Object): T {
...
return Object.create(prototype, descriptors) as T;
}
The signature for Object.create
was changed in TypeScript 2.2. Object.create
的签名在TypeScript 2.2中已更改。
Prior to TypeScript 2.2, the type definition for Object.create
was: 在TypeScript 2.2之前, Object.create
的类型定义是:
create(o: any, properties: PropertyDescriptorMap): any;
But as you point out, TypeScript 2.2 introduced the object
type: 但正如您所指出的, TypeScript 2.2引入了object
类型:
TypeScript did not have a type that represents the non-primitive type, ie any thing that is not
number
| TypeScript没有表示非基本类型的类型,即任何不是number
东西string
|string
|boolean
|boolean
|symbol
|symbol
|null
|null
|undefined
.undefined
。 Enter the new object type. 输入新的对象类型。With object type, APIs like Object.create can be better represented. 使用对象类型,可以更好地表示Object.create等API。
The type definition for Object.create
was changed to: Object.create
的类型定义已更改为:
create(o: object, properties: PropertyDescriptorMap): any;
So the generic type T
in your example is not assignable to object
unless the compiler is told that T
extends object
. 所以通用类型T
在你的例子是不能分配给object
,除非编译器被告知T
扩展object
。
Prior to version 2.2 the compiler would not catch an error like this: 在2.2版之前,编译器不会捕获这样的错误:
Object.create(1, {});
Now the compiler will complain: 现在编译器会抱怨:
Argument of type '1' is not assignable to parameter of type 'object'. 类型“1”的参数不能分配给“对象”类型的参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.