Home > Enterprise >  Nestjs override base service method
Nestjs override base service method

Time:10-20

I have the following method inside a base service:

crud-base.service.ts

export class CrudBaseService {
  constructor(protected repo: MongoRepository<any>) {}
  
  async create(data) {
    // do stuff
  }
}

Here I want to be able to create my custom create method so I name my method the same as the one from base service

items.service.ts

@Injectable()
export class ItemsService extends CrudBaseService {
  constructor(
    @InjectRepository(Item)
    private itemsRepository: MongoRepository<Item>,
  ) {
    super(itemsRepository);
  }
}

async create(data) {
    // overriding base service method
}

Gives me the following error:

TS2416: Property 'create' in type 'ItemsService' is not assignable to the same property in base type 'CrudBaseService'

CodePudding user response:

The signature of both functions must be the same, that means parameters and return type must be the same. You should make this explicit.

export class CrudBaseService {
  constructor(protected repo: MongoRepository<any>) {}
  
  async create(data: YourType): Promise<YourReturnType> {
    // do stuff
  }
}


@Injectable()
export class ItemsService extends CrudBaseService {
  constructor(
    @InjectRepository(Item)
    private itemsRepository: MongoRepository<Item>,
  ) {
    super(itemsRepository);
  }
}

// this should work
async create(data: YourType): Promise<YourReturnType> {
    // overriding base service method
}
  • Related