Issue
I often have the situation that I want to make a specific entry selectable from a set of data in a component (e.g. via select-box or as an entry in a table).
The way I want to use the data, however, often requires additional fields such as the "label: string" field in the case of a select box.
In order for this to succeed, I usually enrich the user data with the required fields. For this I either write my own type (e.g. "ItemWithLabel") or implement this inline (Item & {label:string}
) as shown in the example below:
@Component({
template: '
<my-select-component [data]="items$ | async">
</my-select-component>
'
})
export class MyComponent {
items$: Observable<(Item & {label:string})[]>
constructor(private myDataService: MyDataService) {
this.items$ = this.myDataService.getItems()
.pipe(
// map the data to ensure it fits (Item & {label:string})[]
);
}
}
Now this seems to me to be not very clean or very complex. Is there a simpler/more elegant way of doing this?
Solution
Seems like a good use case for a generic type:
type Labelled<T> = T & { label: string };
items$: Observable<Labelled<Item>>[]>
No need to declare a new type every time.
Or if you want to keep the original data separate:
type Labelled<T> = {
data: T;
label: string;
};
Answered By - Chris Hamilton
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.