Gerrit Begher
Gerrit Begher

Reputation: 403

Typescript: Objects with a single key

Consider the following (partially typed) function:

const fn = <T, ?? ...>(name: ??, value: T) => ({ [name]: value })

Is it possible to complete the typing this such that

fn("hello", someT)

would have type

{ hello: T }?

If not: Is there another approach giving a similar result?

I was thinking of something along the lines of

<K extends string, T>(name: K, value: T): { [k: K]: T} => ...

but this does not work.

Upvotes: 1

Views: 759

Answers (1)

Aluan Haddad
Aluan Haddad

Reputation: 31823

Yes.

Use a type parameter to capture the literal type of the key, a subtype of string, and use it to define a mapped type

const fn = <T, N extends string>(name: N, value: T) => <{[P in N]: T}>({
  [name]: value
});

Unfortunately, the type assertion is required.

const hasPOfNumber = fn('p', 52);

console.log(hasPOfNumber.p);

Upvotes: 4

Related Questions