I cannot even find proper words to formulate the question. Here is a simplified code of what I want to achieve.
class Test<T, TId extends keyof T> {
public create(id: T[TId]): T {
return {
[TId]: id, // Error here. I want to set property `TId` to value `id`,
} as T;
}
}
interface A {
id: number;
}
interface B {
fileName: string;
}
new Test<A, 'id'>().create(123); // Want to get { id: 123 }
new Test<B, 'fileName'>().create('file'); // Want to get { fileName: 'file' }
Error is: Conversion of type '{ [x: number]: T[TId]; }' to type 'T' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. 'T' could be instantiated with an arbitrary type which could be unrelated to '{ [x: number]: T[TId]; }'.ts(2352)