'Vue TypeScript type props from extended component
We have a base Interactive component, which by design is supposed to be the base for other components to consume and add their own spin on. For example, the Button component renders the Interactive as a basis, and extends functionality as well as adding styles.
As such, all the props from the props definition of the Interactive component should be added as props on the parent Button.
Previously we implemented this as such:
{
props: {
...Interactive.props,
aCustomProp: {/* ... */}
}
Since we are converting to TypeScript, this is not valid Vue, and although works seems like was a bad implementation and "hacky". Lesson learned there. We want to avoid the usage of mixins as personal preference of the team, and ideally would like to not duplicate prop definition in each component that uses the Interactive child.
I think extends: Interactive might be the solution, however we end up in a position where props.disabled can not be inferred by TypeScript.
Essentially, how I can extend a component and have TS infer its props?
Interactive.vue
export default defineComponent({
props: {
disabled: { type: Boolean, required: false, default: false },
to: { type: String, required: false, default: null }
}
});
Button.vue
import Interactive from './Interactive.vue';
export default defineComponent({
props: {
primary: { type: Boolean, required: false, default: false },
},
extends: Interactive,
setup(props) {
if (props.disabled) {
// Do something
}
}
});
The above gives the error Property 'disabled' does not exist on type 'Readonly<{ name: string; loading: boolean; } & {}>'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
