[Blazor] Type inference improvement: RenderFragment parameters
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 6h
- Merged PRs (30d)
- 290
Description
### Is there an existing issue for this?
- [x] I have searched the existing issues
### Is your feature request related to a problem? Please describe the problem.
Consider 3 Blazor components: `MyWidgetsPage`, `WidgetsDisplay`, and `DataGrid`. `DataGrid` is marked with `[CascadingTypeParameter(nameof(TGridItem))]`.
`WidgetsDisplay` contains an instance of `DataGrid`. Any children of that component, such as a `TemplateColumn`, will be automatically passed the type argument `Widget`. `WidgetsDisplay` also has a `[Parameter] RenderFragment` called `ExtraColumns` that is used inside the data grid.
`MyWidgetsPage` has a `WidgetsDisplay`. In the `ExtraColumns` argument, there are some more `TemplateColumn`s. Theoretically, the Blazor compiler should be able to infer the type argument `Widget`, but it currently has no way of knowing that `ExtraColumns` is only used in a context where it's given a cascading type parameter. So, I have to manually specify `T="Widget"` in each child component. Not a huge problem, but still an area where Blazor could improve.
### Describe the solution you'd like
I would love to be able to specify on a RenderFragment parameter what type variables it has access to. Something like:
```cs
[CascadingType(nameof(DataGrid.TGridItem), nameof(Widget)), Parameter] public RenderFragment ExtraColumns { get; set; }
```
Current workarounds include just specifying the type parameters explicitly (as in the code below), or making the whole `WidgetDisplay` component generic with a type constraint to `Widget`.
### Additional context
Example code from the problem statement:
`DataGrid.razor`
```razor
@typeparam TGridItem
@attribute [CascadingTypeParameter(nameof(TGridItem))]
@code {
[Parameter] public IEnumerable Items { get; set; }
[Parameter] public RenderFragment ChildContent { get; set; }
}
```
`WidgetsDisplay.razor`
```razor
@ExtraColumns
Do Something
@code {
[Parameter] public IEnumerable Widgets { get; set; }
[Parameter] public RenderFragment ExtraColumns { get; set; }
}
```
`MyWidgetsPage.razor`
```razor
@context.GetBar()
```
Contributor guide
Research direction
Start with the DataGrid.razor, WidgetsDisplay.razor, and MyWidgetsPage.razor examples to reproduce the missing type inference. Then trace the Blazor compiler handling for RenderFragment parameters and cascading type parameters. Done means a RenderFragment declaration can expose the relevant type variable so nested TemplateColumn components infer Widget without explicit TGridItem arguments.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- compilers, frontend
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100