angular / angular/components

feat(tree): typescript/strong typing of nodes

Open
#30,502 2 comments 6 reactions 0 assignees View on GitHub
area: cdk/tree feature P3
Dominant language
TypeScript
Stars
25k
Forks
6.8k
Avg merge
1d 8h
Merged PRs (30d)
91

Description

### Feature Description

Currently `*matTreeNodeDef` types the resulting variable as `any`:

![Image](https://github.com/user-attachments/assets/f0caae8a-9a16-44d2-8697-7daee05fcc03)

### Use Case

>enable you to build web apps with confidence!

The lack of strong typing is really problematic for bigger projects, and it feels like a downgrade in developer experience compared to custom build trees.

Further motivation for this has been described in:

https://github.com/angular/components/issues/16273
https://github.com/angular/angular/issues/28731
https://nartc.me/blog/typed-mat-cell-def/
https://github.com/angular/components/issues/22290

Workaround copied from https://github.com/angular/components/issues/22290:
```ts
import { Directive, input } from '@angular/core';
import { MatTree, MatTreeNodeDef } from '@angular/material/tree';

@Directive({
selector: '[matTreeNodeDef]',
providers: [
{ provide: MatTreeNodeDef, useExisting: TypeSafeMatTreeNodeDefDirective },
],
})
export class TypeSafeMatTreeNodeDefDirective extends MatTreeNodeDef<
NoInfer
> {
readonly matTreeNodeDefTree = input.required>();

static ngTemplateContextGuard(
dir: TypeSafeMatTreeNodeDefDirective,
ctx: any,
): ctx is { $implicit: T; index: number } {
return true;
}
}
```

```diff
-
+
...
-
+
```

Contributor guide

Open the contributing guide

Research direction

Start with the MatTreeNodeDef, MatTree, and matTreeNodeDef entry points shown in the issue, then compare the linked TypeSafeMatTreeNodeDefDirective workaround and referenced discussions. Done means the variable declared by *matTreeNodeDef is strongly typed without requiring the workaround, with the documented tree usage still working.

Written by the indexing model from the issue text.

Assessment

Tech stack
angular, typescript
Domain
developer-experience, frontend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.