Samuel
Samuel

Reputation: 1426

Setting the `type` of @Input at runtime : Angular & typescript

I have a component which displays data and also emit event on a click (after doing some calculation on it)

So display.component

type ClickEvent = {
  data: any, //<-- it should be same as @input data
  something: number;
}
export class DisplayComponent{

 @Input() data: any;

 @Output() clicked = new EventEmitter<ClickEvent>() 

 buttonClicked(){
    this.clicked.emit({data: this.data , something: 2})
  }

}

I want to make sure that the @Output and @Input are of same type. So the the user can use intellisense to access the $event which is being sent as this.clicked.emit(this.data)

Upvotes: 1

Views: 182

Answers (1)

IAfanasov
IAfanasov

Reputation: 4993

Generics to the rescue

type ClickEvent<TEventData> = {
  data: TEventData, 
  something: number;
}
export class DisplayComponent<TComponentData>{

 @Input() data: TComponentData;

 @Output() clicked = new EventEmitter<ClickEvent<TComponentData>>();

 buttonClicked(){
    this.clicked.emit({data: this.data , something: 2})
  }

}

Upvotes: 2

Related Questions