How to create an object type with a custom key in a function?

Viewed 186

I want to create a function that accepts a key and a value, and return a new object with that data. For example:

createObject('name', 'Foo'); // { name: "Foo" }

And I also want to make that function type-safe, which means that it should return a type with the key and its value type. For example:

type ReturnedType = { name: string };

I tried to do that, but I am getting an error:

type Obj<K extends string, V> = {
  [key in K]: V
};

function createObject<K extends string, V>(key: K, value: V): Obj<K, V> {
  // Type '{ [x: string]: V; }' is not assignable to type 'Obj<K, V>'.
  return {
    [key]: value
  }
}

const person = createObject('data', {
  name: 'Foo',
  age: 10
});

console.log(person.data.name);

Playground link.

0 Answers
Related