function that returns object as type of interface if the object parameter matches type literal of interface. in typescript

You can use TypeScript's keyof operator and generics to create a function that returns an object with a specific interface. Here's an example:

index.ts
interface Person {
  name: string;
  age: number;
}

function createPerson<T extends keyof Person>(prop: T, value: Person[T]): Person {
  return {
    [prop]: value,
    // Default values for the rest of the properties
    name: "",
    age: 0,
  };
}

const person = createPerson("name", "John");
// person is inferred as type Person { name: string; age: number; }
console.log(person);
387 chars
18 lines

In this example, the createPerson function takes two parameters: prop and value. The prop parameter is a keyof Person, meaning it can only be one of the keys in the Person interface ("name" or "age" in this case). The value parameter is the value to be assigned to the corresponding property.

The return type of the function is inferred based on the key-value pair provided in the function call. If prop is "name", then the return type will be inferred as Person { name: string; age: number; }.

This approach allows you to create a type-safe function that returns an object with a specific interface, based on the input parameters.

gistlibby LogSnag