nicojs / typed-inject

Type safe dependency injection for TypeScript
Apache License 2.0
439 stars 23 forks source link

How to handle class inheritance with extra deps? #9

Closed moltar closed 4 years ago

moltar commented 5 years ago

How to handle a case where the sub class needs all of the parent class deps, but also needs to add extra deps?

Thanks!

nicojs commented 5 years ago

Hmm I see what you mean.

class Foo {
  constructor(public foo: string) { }
  public static inject = tokens('foo');
}
class Bar extends Foo {
  constructor(foo: string, public bar: string) {
    super(foo);
  }
  public static inject = tokens('foo', 'bar');
}

This gives a compile error:

Class static side 'typeof Bar' incorrectly extends base class static side 'typeof Foo'.
  Types of property 'inject' are incompatible.
    Type '["foo", "bar"]' is not assignable to type '["foo"]'.
      Types of property 'length' are incompatible.
        Type '2' is not assignable to type '1'.ts(2417)

Do you really need the parent class itself to be injectable as well? If not, you could simply remove the inject property from it.

I guess redefining a static field is not supported with typescript 🤷‍♂️

moltar commented 5 years ago

It is true that I don't need the parent class to be injectable. I was just trying to keep it DRY.

nicojs commented 5 years ago

Ah yes, if you don't override the constructor in the child class, I see. I guess it's a limitation of typed-inject.

Do you think it should be added to the readme? Thanks for the heads up!

nicojs commented 4 years ago

I won't add it to the readme as it adds complexity. People can find this issue if they search for it.