21

下面的代码在 TypeScript 2.1.6 上运行良好:

function create<T>(prototype: T, pojo: Object): T {
    // ...
    return Object.create(prototype, descriptors) as T;
}

更新到 TypeScript 2.2.1 后,我收到以下错误:

错误 TS2345:“T”类型的参数不可分配给“对象”类型的参数。

4

2 回答 2

22

更改函数的签名,以便泛型类型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;
}
于 2017-02-23T16:40:30.867 回答
10

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

于 2017-02-23T17:52:41.523 回答