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.
{ [key: string]: unknown }refers to an object withstringas indexable keys: this means that you cannot simply assign any arbitrary object to it. This makes it a narrower type thanobject. You can assign{ [key: string]: unknown }toobject, but not the other way round.