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'.
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.
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.
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, 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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With