Struggling to articulate my question, here is a simplified code snippet outlining what I aim to accomplish.
class Example<T, TId extends keyof T> {
public create(id: T[TId]): T {
return {
[TId]: id, // Encounter an error at this point. Objective is to assign the value `id` to property `TId`.
} as T;
}
}
interface Person {
id: number;
}
interface Place {
cityName: string;
}
new Example<Person, 'id'>().create(123); // Intention is to receive { id: 123 }
new Example<Place, 'cityName'>().create('New York'); // Expecting { cityName: 'New York' }
Error message:
Conversion of type '{ [x: number]: T[TId]; }' to type 'T' may be problematic due to lack of overlap between the two types. If intentional, convert the expression to 'unknown' first. Instantiation of 'T' could result in an incompatible type with '{ [x: number]: T[TId]; }'.ts(2352)