Skip to content

Feature: fx.AsType[T] as generic wrapper over fx.As(new(T)) #1285

Description

@wbhob

Is your feature request related to a problem? Please describe.

Not related to a problem. In Go 1.26, there is a new errors.AsType that is more ergonomic and succinct than errors.As. I am proposing a similar annotation in Fx that uses generics and emulates the implementation in errors. https://go.dev/doc/go1.26#errorspkgerrors

Describe the solution you'd like
A clear and concise description of what you want to happen.

A succinct implementation could look like this:

func AsType[T any]() Annotation {
     return As(new(T))
}

I am guessing this would most likely be inlined by the go compiler. An alternative implementation that is guaranteed to be inlined:

func AsType[T any]() Annotation {
	return &asAnnotation{targets: []any{new(T)}}
}

A tradeoff here, however, is that you would only be able to annotate one type at a time. Whereas today you can write fx.As(new(T), new(V)), this implementation would force you to write fx.AsType[T](), fx.AsType[V](), though fx.Self already requires this distinction, and this makes the annotations list more clear. Those who prefer the brevity of multiple news in fx.As can keep using fx.As the same as before.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

This could easily be implemented in user land, but feels like a library-level benefit that all users can benefit from. A user land implementation:

func AsType[T any]() fx.Annotation {
     return fx.As(new(T))
}

Is this a breaking change?
We do not accept breaking changes to the existing API. Please consider if your proposed solution is backwards compatible. If not, we can help you make it backwards compatible, but this must be considered when we consider new features.

This change uses generics, which would force Go 1.18+. The library appears to promise support only for the last two versions in similar fashion to the Go team, and thus is NOT a breaking change for all consumers on Go 1.24+.

Additional context
Add any other context or screenshots about the feature request here.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions