简体   繁体   中英

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:

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:

error TS2345: Argument of type 'T' is not assignable to parameter of type 'object'.

Change signature of the function, so that generic type T extends type object , introduced in Typescript 2.2. Use this syntax - <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.

Prior to TypeScript 2.2, the type definition for Object.create was:

create(o: any, properties: PropertyDescriptorMap): any;

But as you point out, TypeScript 2.2 introduced the object type:

TypeScript did not have a type that represents the non-primitive type, ie 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.

The type definition for Object.create was changed to:

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 .

Prior to version 2.2 the compiler would not catch an error like this:

Object.create(1, {});

Now the compiler will complain:

Argument of type '1' is not assignable to parameter of type 'object'.

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