How can I get the argument type of an SFC component's event?

35 views Asked by At

Say I have an SFC component with a save emit:

// ChildComponent.vue
const emit = defineEmits<{
  save: [data: { new: Row[]; removed: Row[] }];
}>();

If I want to use the new & removed in a parent component I would do this:

// ParentComponent.vue
<ChildComponent 
  @save="($event) => {
    performAPIRemove($event.removed); // TypeScript correctly infers `$event` type
  }"
/>

However, I want to define the event callback as a named function. How do I get the type of the child component's emit?

// ParentComponent.vue
// Something along the lines of...
function saveCallback(event: typeof ChildComponent.emits.save) {
  performAPIRemove(event.removed)
}
1

There are 1 answers

0
David ROSEY On

I,

You can create an interface in a ,ts file ex :

export interface ChildEmits {
  new: Row[];
  removed: Row[];
}

Then, in your child component, you can use this type :

const emit = defineEmits<{
  save: [data: ChildEmits];
}>();

And you can type your callback parameter like this :

function saveCallback(event: ChildEmits) {
  performAPIRemove(event.removed)
}