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.ts387 chars18 linesIn 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