If I have:
const keys = ['a', 'b', 'c']
const obj = {}
for (const key of keys) {
obj[key] = key
}
Then the error is:
Element implicitly has an 'any' type because expression of type '"a" | "b" | "c"' can't be used to index type '{}'.
Property 'a' does not exist on type '{}'
If I add type to it:
const keys = ['a', 'b', 'c'] as const
type Key = typeof keys[number]
type Obj = Record<Key, Key>
const obj: Obj = {}
for (const key of keys) {
obj[key] = key
}
Then the error is:
Type '{}' is missing the following properties from type 'Obj': a, b, c
I can assert the type with
const obj: Obj = {} as Obj
But for the sake of learning, is there a way to tell TS that the final object will have type Obj
without having to use type assertion?
TS Playground