Reputation: 375
I am implementing a class like the following:
import * as User from './user';
export class Database {
constructor() {
for (const method in User) {
this[method] = User[method];
}
}
}
Where the ./user file contains:
export async function findById(id: number): Promise<User | null> {
return //
}
export async function findByName(name: string): Promise<User | null> {
return //
}
I can now use the Database class to perform operations, however there are no TypeScript hints since these are lost by dynamically reassigning the methods. I also have to include a @ts-nocheck in the Database file as I am otherwise getting the error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof import
Implementing a predefined interface also will not work due to it not registering the dynamic types (which is logical as these are loaded in at runtime). How do I implement a dynamic interface for this?
Big thanks
Upvotes: 2
Views: 284
Reputation: 375
With suggestions from Keith I changed it to:
import * as User from './user';
export const Database = class _Database {
constructor() {
Object.assign(this, User);
}
} as { new (): typeof User };
This solved the TypeScript errors (yay)
Upvotes: 1