为什么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