microsoft / tsyringe

Lightweight dependency injection container for JavaScript/TypeScript
MIT License
5.18k stars 172 forks source link

Error registering a generic interface/class #206

Open brendan-rice opened 2 years ago

brendan-rice commented 2 years ago

Describe the bug

I have a generic cache class (see below).

import { injectable } from 'tsyringe';
import { Cache } from '../contract/cache';

@injectable()
export class CacheImpl<DataT> implements Cache<DataT> {
  private data = {} as Partial<DataT>;

  getValue<K extends keyof DataT>(key: K): DataT[K] {
    return this.data[key];
  }

  setValue<K extends keyof DataT>(key: K, value: DataT[K]): void {
    this.data[key] = value;
  }
}

Here is how I try to register it:

container.register<Cache<MyDto>>(
  TYPES.ModuleAccessDetailsCache,
  {
    useClass: CacheImpl<MyDto>
  },
  {
    lifecycle: Lifecycle.Singleton
  }
);

I get the following errors when I try to compile

image

Are generic types supported and how can I register them?

To Reproduce

  1. Create a generic class/interface
  2. Try to register it

Expected behavior The registration should be successful

Version: