typescript 错误 TS2345:“T”类型的参数不可分配给“对象”类型的参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42421501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
error TS2345: Argument of type 'T' is not assignable to parameter of type 'object'
提问by Nenad
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”类型的参数不可分配给“对象”类型的参数。
回答by Nenad
Change signature of the function, so that generic type T
extends type object
, introduced in Typescript 2.2. Use this syntax - <T extends object>
:
更改函数的签名,以便泛型类型T
扩展 type object
,在 Typescript 2.2 中引入。使用此语法 - <T extends object>
:
function create<T extends object>(prototype: T, pojo: Object): T {
...
return Object.create(prototype, descriptors) as T;
}
回答by Seamus
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 introducedthe object
type:
但正如你所指出的,TypeScript 2.2 引入了object
类型:
TypeScript did not have a type that represents the non-primitive type, i.e. any thing that is not
number
|string
|boolean
|symbol
|null
|undefined
. Enter the new object type.With object type, APIs like Object.create can be better represented.
TypeScript 没有表示非原始类型的类型,即任何不是
number
| 的东西。string
|boolean
|symbol
|null
|undefined
. 输入新的对象类型。使用对象类型,可以更好地表示 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
extends ,否则您示例中的泛型类型不可分配给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”类型的参数不能分配给“对象”类型的参数。