Add typing for NgElement Outputs
- Langage dominant
- TypeScript
- Étoiles
- 101k
- Forks
- 27.5k
- Merge moyen
- 1 j 19 h
- PR mergées (30 j)
- 288
Description
### Which @angular/* package(s) are relevant/related to the feature request?
elements
### Description
I was experimenting with Angular's custom elements. The [documentation](https://angular.io/guide/elements) mentions how attributes/inputs of such elements could be typed,
```typescript
declare global {
interface HTMLElementTagNameMap {
'my-dialog': NgElement & WithProperties<{content: string}>;
'my-other-element': NgElement & WithProperties<{foo: 'bar'}>;
…
}
}
```
but it does not mention how the events/outputs could be typed.
### Proposed solution
I would propose to either add (similar to the WithProperties) a WithEvents/WithOutputs type or even better to add a wrapper type that does the merging of addEventListener signatures better:
Using the `type-fest` library my solution is
```typescript
import { Merge, UnionToIntersection } from "type-fest";
import { NgElement, WithProperties } from "@angular/elements";
export type TypedNgElement, Outputs extends Record = {}> = Merge<
NgElement,
WithProperties &
UnionToIntersection<
{
[K in keyof Outputs]: {
addEventListener(type: K, listener: (event: CustomEvent) => void, options?: boolean | AddEventListenerOptions): void;
};
}[keyof Outputs]
>
>;
```
That can later be used as follows:
```typescript
declare global {
interface HTMLElementTagNameMap {
"my-custom-element-selector": TypedNgElement<
{
inputOne: SomeType;
inputTwo?: boolean;
},
{
outputOne: SomeType;
outputTwo: void;
}
>;
}
}
```
### Alternatives considered
I see alternatives (as I mentioned in the solution) in the way the type is introduced.
Guide de contribution
Ouvrir le guide de contribution
Piste de recherche
Commencez par lire le package @angular/elements et les types existants NgElement et WithProperties, puis examinez l’exemple de la documentation sur les custom elements. Comparez les approches proposées WithEvents, WithOutputs et les types wrapper, et identifiez le comportement de typage qui devrait être couvert. Le travail est considéré comme terminé lorsqu’une API publique approuvée peut typer les événements de sortie des custom elements sans affaiblir le typage existant des entrées.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Évaluation
- Stack technique
- typescript
- Domaine
- frontend
- Type d'issue
- Fonctionnalité
- Difficulté
- 5/5
- Temps estimé
- Plus d'une semaine
- Activité
- À l'abandon
- Clarté
- Plutôt claire
- Accessibilité débutants
- 35/100