#explain difference (type for shapeless object)

3 messages · Page 1 of 1 (latest)

cosmic raven
#
// 1
type TObj1 = { [key: string]: unknown }
// 2
type TObj2 = { [_ in K]: unknown }
// 3
type TObj3 = Record<string, unknown>

as far as I understand, all 3 behave identiacally. If I am wrong, what's the difference among them? It must be pretty slight

spark musk
#

Record<K, V> is a normal type that typescript defines, it's exactly { [P in K]: V } (Ref)
so 2 and 3 are exactly the same, because 3 just resolves to 2

1 and 2 differ when the key is a literal. mapped types define concrete keys, while index signatures say "when the key K is present, it has the value V"
so their behavior is the same when the key is the entire string, for example. when string is used in a mapped type, it behaves exactly like an index signature over string.

cosmic raven