我什至找不到合适的词来提出这个问题。这是我想要实现的简化代码。
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' }
错误是: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)