爲什麼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
}
非常感謝,有沒有推薦的方式來合併對象在typescript中保留類型信息?我重構了斷言的對象,它的工作,只是覺得很hacky。 const merged = {... base,anObject} –
laramie
@laramie我不知道如何。相反,我會使用Object.assign作爲解決方法。 – weakish