angular: Invalid `inject()` function typing

Which @angular/* package(s) are the source of the bug?


Is this a regression?



inject()'s type description seems to be invalid:

Return type should be T | null only if flag is set to InjectFlags.Optional meaning that the signature should be something like this:

 export function ɵɵinject<T>(token: ProviderToken<T>): T; 
 export function ɵɵinject<T>(token: ProviderToken<T>, flags?: InjectFlags.Default | InjectFlags...): T; 
 export function ɵɵinject<T>(token: ProviderToken<T>, flags?: InjectFlags.Optional): T | null; 
 export function ɵɵinject<T>(token: ProviderToken<T>, flags = InjectFlags.Default): T|null

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

No response

Please provide the environment you discovered this bug in (run ng version)

No response

Anything else?

No response

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 7
  • Comments: 17 (16 by maintainers)

Commits related to this issue

Most upvoted comments

Another thing, it may be a bit of a silly one, but if we are going to replace the flags with an object could we maybe rename self to something like onlySelf, untilSelf or similar? I think self is a bit less clear, or is that just me?

@dario-piotrowicz good question. I think it’d be valuable to keep the mapping between the current flags (which also map to the decorators like @Self, @Host, etc) and the inject flags, so it’s easier for developers to transition to the options object. However, we should also consider this improvement (may be we can add extra flags, which would be just aliases) and we can have an additional discussion to decide on the final set of flags once the draft PR is ready.

Quick update: we’ve discussed this topic with the team and we want to move forward with a PR that would:

  • add the support for an object as the second argument in the inject and Injector.get functions (the Injector.get should be a separate commit), while keeping the support for the current format as well for backwards compatibility
  • add the deprecation annotation to the type signatures where an old format is used, with a recommendation to use a new object-based format

One more thing thing to consider is the difference between the inject and Injector.get signatures: the Injector.get has an extra argument to provide a default value if none was found in the DI. Ideally, it’d be great to fully align inject and Injector.get, but it would be a separate effort.

@yjaaidi please let us know if you might be interested in creating a PR to add support for the options object.

A PR is welcome, that would allow for a TGP (running all g3 tests) to see what the impact of such a change would be.