Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'.

like image 226
Nenad Avatar asked Feb 23 '17 16:02

Nenad


People also ask

What is error TS2345?

error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'string'. Type Annotations. These are TypeScript's way of recording the intended contract for a function or variable.

Is not assignable to parameter of type?

The error "Argument of type string | undefined is not assignable to parameter of type string" occurs when a possibly undefined value is passed to a function that expects a string . To solve the error, use a type guard to verify the value is a string before passing it to the function.


2 Answers

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;
}
like image 138
Nenad Avatar answered Oct 18 '22 21:10

Nenad


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, 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.

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'.

like image 38
Seamus Avatar answered Oct 18 '22 20:10

Seamus