I have a class which is actually a Service in NestJS, so the problem I faced is that I cannot type it properly. I mean of course we can do an interface and say that class implements it, but what if I need to use it in generic. Let's take a look what I mean.
For example I want to do a Provider that can choose right class according to some data for example .env, for this purpose we should write a generic
type ServiceProviderType<T> = Record<string, T>;
Now the implementation of such a Provider
const Provider: ServiceProviderType<Interface> = {
default: DefaultService //--------------Problem occurs here
custom: CustomService
}
Error says that typeof DefaultService
cannot be assigned to interface cause it doesn't have required methods, even though it has.
For Example this is Interface
export interface ServiceInterface {
getResult(expression: string): string;
exponentialToDecimal(exponential: string): string;
}
and this is Class
@Injectable()
export class DefaultService implements Interface {
constructor(
@Inject(EXPRESSION_COUNTER_SERVICE)
private readonly expressionCounterService: ExpressionCounterService,
@Inject(REGEXP_CREATOR_SERVICE_INTERFACE)
private readonly regExCreatorService: RegExCreatorService,
) {}
getResult(expression: string): string {
//some code return string
}
exponentialToDecimal(string): {
//some code return string
}
}
DefaultService
is the constructor while that T
would represent an instance of T
, that's why you got that error. You could use the Type<T>
utility from @nestjs/common
or write your own.