Beginning with TypeScript, I am trying to use keyof to define dynamic properties on a class:
type UserType = {
id: number,
name: string,
}
class Domain<T> {
_data: T;
[K in keyof T]: T[K]; // Does not build:
// (1) A computed property name must be of type
// 'string', 'number', 'symbol', or 'any'
// (2) Cannot find name 'keyof'
constructor(data: T) {
this._data = data;
Object.keys(data).forEach((key) => Object.defineProperty(this, key, { get: () => this._data[key] }));
}
}
const joeData: UserType = {
id: 1,
name: 'Joe',
}
const joe = new Domain(joeData); // type: Domain<UserType>
console.log(joe.id);
I did write this code using the same (working) syntax as:
type Foo<T> = {
[K in keyof T]: T[K];
}
Any hints on how to fix the issue?