#Inferring types with inject

4 messages · Page 1 of 1 (latest)

warm mica
#

Hi, I was wondering if the following is some limitation of TypeScript or if I'm doing sth. wrong.

I have the following library code:

// from PrimeNG, I can't change that:
class DynamicDialogConfig<DataType = any, InputValuesType extends Record<string, any> = {}>{
  data?: DataType;
  inputValues?: InputValuesType;
}

and using it like this:

interface WetternutzerDialogData {
  nutzer: INutzer;
}

config = inject(DynamicDialogConfig<WetternutzerDialogData>) ;

resolves in config: DynamicDialogConfig<any, any> - I could cast that but... is there a better way?
When I use it like this

const b = config.data.nutzer

nutzer gets highlighted but I don't get an error if I mistype it

open gazelle
# warm mica Hi, I was wondering if the following is some limitation of TypeScript or if I'm ...

This is basically a limitation of TypeScript, but also a reality of the runtime. The generic type parameters are a TypeScript compiler fiction. There is zero difference at runtime between DynamicDialogConfig<Foo> and DynamicDialogConfig<Bar>. They are the same class.
And DI in Angular works based on the injection token, which in this case is just the class. So there is no way to inject DynamicDialogConfig<Bar> specifically, because at runtime when inject needs to look up the value all it can use is DynamicDialogConfig.
You can of course write inject<DynamicDialogConfig<WetternutzerDialogData>>(DynamicDialogConfig), but this is not any more type-safe than a manual cast. If the provider provided DynamicDialogConfig<FooBar>, inject<DynamicDialogConfig<WetternutzerDialogData>>(DynamicDialogConfig) would still give it to you without any compiler or runtime errors.

warm mica
#

TIL! Too bad, at least it makes its usage a bit clearer, thx for the explanation

twilit adder