I'm new to typescript and I'm trying to define a class properly that turns an object of a certain type to a class with the same properties. However, I can't properly define the keys on this class since they are generic:
interface RawAnswer {
__typename: string;
id: string;
meta: Record<string, unknown>;
}
class TrackedAnswer<T> {
// This doesn't work:
// [K in keyof T]: T<K>
constructor(obj: T) {
Object.entries(obj).forEach(([key, value]) => {
// this is just an example, I'm aware that this is useless
this[key] = value;
});
}
}
const raw: RawAnswer = { __typename: "StringAnswer", id: "123", meta: {} };
const answer = new TrackedAnswer(raw);
I'd like the TrackedAnswer
class to have the same index signature as RawAnswer
in this case. Can someone help me out?