Here's a class that is constructed to augment a data object with methods.
export default class ViewModel<T> {
constructor(props: T) {
Object.assign(this, props);
}
foo() {
console.log('This class and children have methods as well as data');
}
}
Is it possible to have TypeScript understand that all the props of T exist on the instances of ViewModel<T>?
type User = { id: number; name: string };
const m = new ViewModel<User>({ id: 1, name: 'Alice' });
m.foo(); // fine
console.log(m.id); // Property 'id' does not exist
If not, is there a better way to wrap a plain JS object with methods that access its data properties? I'm not attached to this abstract class and would be fine with UserViewModel in the above case, but the codebase already has many different T types and I'd prefer to re-use them if possible. (E.g. make UserViewModel reference User instead of duplicating much of that type's definition.)
I know I can also export an interface along with the class, like in Extending `this` in Typescript class by Object.assign , but I'd also like the methods in the class to know what values are available on this.
props? That makes the solution as simple asm.props.id..propseverywhere to hack around the type system.