4

Since JS keys can only be strings, what is the difference between these in TypeScript?

type A = object

type B = {[key: string]: unknown}

This is similar to Difference between 'object' ,{} and Object in TypeScript but the answers there only acknowledge that these two are similar, they don't explain how they are different (or when you might use one versus the other).

For example, I have a type guard:

function isObject(x: any): x is object {
  return typeof x === 'object' && x !== null
}

This type guard isn't enough for code that expects {[key: string]: unknown} so I have to change the guard:

function isObject(x: any): x is {[key: string]: unknown} {
  return typeof x === 'object' && x !== null
}

which works but I'm not sure if I should be changing the caller instead.

Aron Griffis
  • 1,699
  • 12
  • 19
  • `{ [key: string]: unknown }` refers to an object with `string` as indexable keys: this means that you cannot simply assign any arbitrary object to it. This makes it a narrower type than `object`. You can assign `{ [key: string]: unknown }` to `object`, but not the other way round. – Terry Feb 02 '22 at 23:54
  • What's an example of an arbitrary object? Can keys be something other than strings? – Aron Griffis Feb 02 '22 at 23:57
  • Keys can be symbols. And numbers, sort of. Although numbers are stored as strings on the object, indexing objects by string or number is part of the objects type. That said I'm surprised this is allowed: https://tsplay.dev/w16AkN – Alex Wayne Feb 03 '22 at 00:02
  • Thanks Alex, that surprise is part of the reason for this question. I'm hoping for a fuller answer that really demystifies the difference and gives me (and others) more confidence choosing between them. – Aron Griffis Feb 03 '22 at 00:10
  • Here is another confusing difference: https://tsplay.dev/WG540N – Aron Griffis Feb 03 '22 at 00:31

0 Answers0