Thijs Koerselman
Thijs Koerselman

Reputation: 23271

When to choose type `{}` over `object` or does it matter?

I am wondering about the (semantic) difference in Typescript between {} and object.

For example if you have a function which accepts an object, but you do not know or care about its shape, would you declare it as {} or object or does it not matter?

Here's an example:

export async function updateSomeUserData(
  userId: string,
  data: object
): Promise<void> {
  const ref = await getUserDataRef(userId);

  await ref.update({
    ...data
  });
}

I real life you might want to strictly define all possible data properties with optional keys in a type, but I think this kind of situation can happen where you don't want to be so specific.

Upvotes: 1

Views: 64

Answers (1)

Joe Clay
Joe Clay

Reputation: 35797

The difference is quite subtle:

  • Something typed as {} or Object can represent any object.

  • Something typed as object can only represent non-primitive types - in other words, it cannot be a number, string, boolean, symbol, null or undefined.

In both cases, using the obj.member syntax will only allow you to access the members of the Object prototype.

This is what makes {} and Object differ from the any type - the latter doesn't give you any type safety, while the former will only give you type safety for Object prototype members.

To access an arbitrary key, you have to use the obj["member"] syntax, which effectively tells the type system 'I won't know if this member exists until runtime`. As such, you should make sure to null check it!

Upvotes: 1

Related Questions