#How to iterate index signature with for...in?

8 messages · Page 1 of 1 (latest)

tropic trellisBOT
#

@formal perch Here's a shortened URL of your playground link! You can remove the full link from your message.

davidflowmobile#0

Preview:```ts
const fields = {
field1: {key: "field1", type: "text"},
field2: {key: "field1", type: "text"},
field3: {key: "field1", type: "text"},
field4: {key: "field1", type: "text"},
}

type A = Partial<Record<keyof typeof fields, string>>

const a: {[key in keyof typeof fields]: string} =
...```

analog fulcrum
#

!:unsafe-keys

tropic trellisBOT
#
retsam19#0
`!retsam19:unsafe-keys`:

Since TS allows objects to have extra properties not specified in the type, it doesn't assume that all the keys on the type are the only keys on the object. This means that Object.keys returns string[] not a specific type, and for(const key in obj), key is string, (not keyof typeof obj).

If you wish to assume otherwise, this utility is often helpful:

// A signature for `Object.keys` that assumes the only keys are the ones indicated by the type
const unsafeKeys = Object.keys as <T>(obj: T) => Array<keyof T>;
analog fulcrum
#

the first half has the explanation

#

key is widened to string, because fields might have enumerable keys other than what the type says
in reality that isn't the case, but typescript doesn't have a way to notate that

formal cobalt
#

could you encode fields as an array or a Map instead of an object? if so you could avoid this problem

#

the current encoding is duplicative anyway