I am using vue composition api with typescript.
How can I strongly type the component props using typescript typing system?
You define a prop named disabled in MyComponent. vue . ... and then add the component like this, passing in disabled . Note that :disabled="true" and just disabled mean the same thing in both cases - when props are defined or not.
TypeScript also improves developer ergonomics via type-based auto-completion in IDEs. Vue is written in TypeScript itself and provides first-class TypeScript support. All official Vue packages come with bundled type declarations that should work out-of-the-box.
Composition API is a set of APIs that allows us to author Vue components using imported functions instead of declaring options. It is an umbrella term that covers the following APIs: Reactivity API, e.g. ref() and reactive() , that allows us to directly create reactive state, computed state, and watchers.
Troy Kessier's answer is not entirely accurate. I quote the documentation on definecomponent
:
Alternatively if your component does not use any option other than setup itself, you can pass the function directly […]
So there are not two ways of declaring properties, but rather two ways of declaring a component, and each of them provides its own way of typing props.
With the classic way and TypeScript, use PropType
:
import { defineComponent, PropType } from 'vue' export default defineComponent({ props: { someOptionalString: String, someRequiredString: { type: String, required: true }, someObject: { type: Object as PropType<MyObjectType>, required: true }, }, // … })
Notice: PropType
helps to give a correct TypeScript type to the props
parameter in the setup
function. But the underlying Vue type for the props remains Object
and there is currently no way to enforce a better typing for these props passed by the parent component.
As explained in the official docs you can type props in two ways:
Define arops via argument annotation
import { defineComponent } from 'vue' export default defineComponent((props: { foo: string }) => { props.foo })
Or like this
import { defineComponent } from 'vue' export default defineComponent({ props: { foo: String }, setup(props) { props.foo // <- type: string } })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With