1

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.

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.