1

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)

1
  • If your type is predicted, then you can use interface and adds interface as type to both input and output. That's more easy for you to implement. Commented May 19, 2021 at 10:51

1 Answer 1

2

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})
  }

}

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I have made an update in the question. Sincere apologies for changing the question little bit
When I try to assign a value like @Input() data: TComponentData = { p1: 'Val1' } , it doesn't accept it. Says is not assignable to type 'TComponentData'.
that is not that easy to address. Here is the possible solutions: stackoverflow.com/a/52477831/390161

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.