Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strongly typing props of vue components using composition api and typescript typing system

I am using vue composition api with typescript.

How can I strongly type the component props using typescript typing system?

like image 431
geeko Avatar asked Jan 29 '20 11:01

geeko


People also ask

How do you define props in Vue composition API?

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.

Does vue2 support TypeScript?

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.

What is a composition API in Vue?

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.


2 Answers

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.

like image 54
Paleo Avatar answered Oct 09 '22 03:10

Paleo


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   } }) 
like image 43
Troy Kessler Avatar answered Oct 09 '22 03:10

Troy Kessler