Prop Types with TypeScript
Illustrate the usage of TypeScript in Vue.js 3 for defining and validating the types of props.
<template>
<div>
<h1>{{ title }}</h1>
<p>{{ description }}</p>
</div>
</template>
<script lang="ts">
import { defineComponent, PropType } from 'vue';
interface ArticleProps {
title: string;
description?: string;
}
export default defineComponent({
name: 'Article',
props: {
title: {
type: String as PropType<ArticleProps['title']>,
required: true
},
description: {
type: String as PropType<ArticleProps['description']>,
default: ''
}
}
});
</script>
<style scoped>
h1 {
color: #333;
}
p {
color: #666;
}
</style>
A Vue 3 component 'Article' is defined using TypeScript. It has props for 'title' (required) and 'description' (optional with a default value) with their respective types declared. PropType is used to cast the types to be the correct Vue prop types. The template section includes a simple layout with a title and description.