- read

How to Define Props in Vue.js with TypeScript Support

John Philip 56

TypeScript logo by Toothpick

Introduction

In modern applications, components frequently communicate with each other. Vue.js, like many frontend frameworks, facilitates this communication primarily through props. Props enable one-way communication from a parent component to a child component.

However, when we need to enable communication from child to parent components, we utilize ‘emits.’ Emits empower us to propagate functions and values upward through the component hierarchy.

Props Definition with TypeScript support

TypeScript enables us to declare compile time type definitions. This can be really useful in catching bugs earlier in development. To define props in Vuejs, we will leverage the defineProps macro which is a built in API to provide props support. With it, we can define the props our child component expect together with other niceties we will see later.

This article will assume you are using Vuejs 3 with the <script setup lang=”ts”> with typescript support enabled.

Typing Component Props

<script setup lang="ts">
// Declare props using the defineProps function
const props = defineProps({
message: String,
});

// Access props within the component setup
const message = props.message;

</script>

<template>
<h2>{{ message}} from ChildComponent </h2>
</template>

In the provided code, we’re using the Vue.js 3 Composition API with TypeScript to define and access props:

  • We declare props using defineProps({ message: String }), where message is a prop of type String.
  • We access the message prop within the component setup using const message = props.message.

In the template, we display the message prop’s value.

This code snippet demonstrates how to work with props in a Vue.js 3 component using TypeScript and the Composition API.

Typing Component Props with Default values

<script setup lang="ts">
//…