How to create typescript type for component which must have certain props / events? #14228
Unanswered
shameleo
asked this question in
Help/Questions
Replies: 1 comment
-
|
The problem is that DefineComponent type expects exact match. What you need is a type that says "must have at least these events, but can have more". Try this approach: import type { Component } from 'vue'
// Define minimum required emits
type RequiredEmits = {
close: [data: unknown]
}
// Use a generic that extends your requirements
type ModalComponentType<T extends RequiredEmits = RequiredEmits> = Component & {
emits?: T
}
export function showModal(modal: ModalComponentType) {
// ...
}Or even simpler - just check at runtime and keep types loose: import type { Component } from 'vue'
export function showModal(modal: Component) {
// Vue component types are really complex
// sometimes its easier to validate at runtime
}The issue is Vue's DefineComponent has like 8 generic parameters and strict mode makes it worse. For dynamic component patterns like modal managers, I usually go with looser types and add runtime checks if needed. If you really want strict typing, consider making a base modal component that all modals extend - then you type against that base class instead. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Here is my attempt to do it
modal-manager.ts
Modal.vue
App.vue
But it has mijor issue: if component has more events, than I defined, typecheck fails. But it shouldn't. Props / events should be required, but extra props / events must be allowed also. Like it usually works in typescript.
PS I added
"strict": trueintsconfig.jsonBeta Was this translation helpful? Give feedback.
All reactions