Typescript - Dynamic key names in object? Using template literal?

Viewed 885

Is something like the following possible?

type test = <T extends string>(key: T, object: { [`${T}`]: number }) => void
                                                 ^^^^^^^^

I know we can set type literal values using that syntax, but I've played around and don't seem to be able to do it with keys.

However, logically, I feel like it should be possible given mapped keys using as is possible...

Anybody have any insight into this?

1 Answers

You can use Record<T, number> (I recommend) or classic usage:

type test = <T extends string>(key: T, object: { [K in T]: number }) => void

Type objects don't work the same as JS objects.

EDIT

for more fields, use & (merge) operator:

type test = <T extends string>(key: T, object: { [K in T]: number } & {foo: "bar"}) => void

or (better)

type test = <T extends string>(key: T, object: Record<T, number> & {foo: "bar"}) => void
Related