簡體   English   中英

錯誤TS2345:類型'T'的參數不能分配給'object'類型的參數

[英]error TS2345: Argument of type 'T' is not assignable to parameter of type 'object'

下面的代碼適用於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'的參數不能分配給'object'類型的參數。

更改函數的簽名,使泛型類型T擴展類型object ,在Typescript 2.2中引入。 使用此語法 - <T extends object>

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

Object.create的簽名在TypeScript 2.2中已更改。

在TypeScript 2.2之前, Object.create的類型定義是:

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

但正如您所指出的, TypeScript 2.2引入object類型:

TypeScript沒有表示非基本類型的類型,即任何不是number東西 string | boolean | symbol | null | undefined 輸入新的對象類型。

使用對象類型,可以更好地表示Object.create等API。

Object.create的類型定義已更改為:

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

所以通用類型T在你的例子是不能分配給object ,除非編譯器被告知T擴展object

在2.2版之前,編譯器不會捕獲這樣的錯誤:

Object.create(1, {});

現在編譯器會抱怨:

類型“1”的參數不能分配給“對象”類型的參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM