2017-07-29 72 views
2

爲什麼TSC會說「... base」必須是一個對象,我該如何解決這個問題,同時仍然保留「base」對象的類型。爲什麼typecript會抱怨對象必須是傳播類型的對象

function aFunction<T extends object>(base: T) { 
    const anObject = { test:"value" } 
    if (typeof base !== 'object') { return } 

// the following line causes a TSC error, saying that spread types can only be 
// created from object types and highlighting base as the problem... wut? 

    const merged = { ...base, anObject } 
    return merged 
} 

例如,下面沒有編譯器錯誤,但是失去了所有類型的信息'base'。

function aFunction(base: object) { 
    const anObject = { test:value } 
    if (typeof base !== 'object') { return } 

    const merged = { ...base, anObject } 
    return merged 
} 

回答

2

<T extends object>(base: T)裝置base是一個通用型T的。

而TypeScript的類型系統還不瞭解泛型。 (#10727

解決方法:

  1. 重構代碼,不使用...

  2. 等待#10727得到解決。

  3. 更改爲其他類型檢查,例如,流程:

流程報表上你的代碼中沒有錯誤:

/* @flow */ 

function aFunction<T: Object>(base: T) { 
    const anObject = { test:"value" } 
    if (typeof base !== 'object') { return } 

    const merged = { ...base, anObject } 
    return merged 
} 
+0

非常感謝,有沒有推薦的方式來合併對象在typescript中保留類型信息?我重構了斷言的對象,它的工作,只是覺得很hacky。 const merged = {... base,anObject} – laramie

+0

@laramie我不知道如何。相反,我會使用Object.assign作爲解決方法。 – weakish

1

傳播和休息尚不支持仿製藥的時刻。

0

在第一個片段基礎是從對象繼承的type T。那麼你知道在JavaScript中它不是一個強大的關係,因此不是一個is a的關係,所以T不一定是object。 T只是原型繼承了對象。打字稿也沒有對泛型的理解,所以不支持傳播。

在代碼段2 base是對象類型,但打字稿支持對象傳播和解構。對象類型的值可以傳播。此功能主要用於製作對象的副本。所以這就是爲什麼它沒有給出錯誤。

+0

這只是TypeScript作爲#10727的弱點。 – weakish

相關問題