2

I created a reusable component that takes a list of elements of the type any. He works on these elements and in the case of pressing the button returns the state of the list he got. I'm worried about losing typing in this case. Is this a safe solution? I would like the component to be reusable. Is it possible to dynamically cast from any type to a different type?

I tried to cast object in set Input() but it is not possible

export class ReusableTableComponent {
  @Input() list: any[];
  @Output() selectedItems: EventEmmiter = new EventEmmiter<any>;
  selectedItemsList: any[] = [];

  emitChanges() {
  this.selectedItems.emit(this.selectedItemsList)}

}

The problem is, eventEmmiter is returning object type not specific type.

Blackboy
  • 192
  • 2
  • 20

2 Answers2

4

You can use a generic type:

export class ReusableTableComponent {
  @Input() list: T[];
  @Output() selectedItems: EventEmmiter = new EventEmmiter<T>;
  selectedItemsList: T[] = [];

  emitChanges() {
  this.selectedItems.emit(this.selectedItemsList)}

}

Read more about generic types in TypeScript here: https://www.typescriptlang.org/docs/handbook/generics.html

Eliran Eliassy
  • 1,590
  • 12
  • 25
  • Thanks but how i van pass Type to input from patent component ? – Blackboy Jun 07 '19 at 05:33
  • there are an interesting discussion about your question in https://stackoverflow.com/questions/46893991/declare-a-component-with-generic-type?rq=1, but I don't know if relative to your question – Eliseo Jun 07 '19 at 07:06
1

yes you can use dynamic types in Typescript

export class ReusableTableComponent<LIST, EVENTLIST> {
  @Input() list: LIST[];
  @Output() selectedItems: EventEmmiter = new EventEmmiter<EVENTLIST>;
  selectedItemsList: EVENTLIST[] = [];

  emitChanges() {
  this.selectedItems.emit(this.selectedItemsList)}

}
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80