Why does typescript complain that an object must be an object in spread types

Viewed 511

Why does TSC say that "...base" must be an object, how do I resolve this problem while still retaining the types from the "base" object.

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
}

For example, the following does not have a compiler error however loses all type information of 'base'.

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

  const merged = { ...base, anObject }
  return merged
}
3 Answers
Related