6

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.

6
  • { [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. Commented Feb 2, 2022 at 23:54
  • 1
    What's an example of an arbitrary object? Can keys be something other than strings? Commented Feb 2, 2022 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: tsplay.dev/w16AkN Commented Feb 3, 2022 at 0: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. Commented Feb 3, 2022 at 0:10
  • Here is another confusing difference: tsplay.dev/WG540N Commented Feb 3, 2022 at 0:31

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.