Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

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

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...