Typed Component Props
up:: Vue, Nuxt β π TypeScript with Composition API | Vue.js
Interface
We can define the types for props through a TypeScript interface. In this case through a Typescript generic type argument.
<script setup lang="ts">
interface Props {
tags: string[];
}
const props = defineProps<Props>();
</script>
This interface must be in the same file.
We can also skip the interface and declare types straight in the defineProps
method:
<script setup lang="ts">
const props = defineProps<{
tags: string[];
}>();
</script>
Default values
Using the method above, we loose the ability to define default values. We can bring that functionality back in with the withDefaults()
method.
<script setup lang="ts">
export interface Props {
msg?: string
labels?: string[]
}
const props = withDefaults(defineProps<Props>(), {
msg: 'hello',
labels: () => ['one', 'two']
})
<script>
Arrays and Object require arrow syntax
You see it in the example above. When specifying an array or object as a default value, it needs to be written in arrow syntax. I forget this so often and it always throws a type error.