0
0
Vueframework~30 mins

Typing composables in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Typing Composables in Vue 3
📖 Scenario: You are building a small Vue 3 app that uses a composable function to manage a counter. You want to add TypeScript types to your composable to make it safer and easier to use.
🎯 Goal: Create a typed composable function called useCounter that returns a reactive count and an increment function. Use TypeScript types to define the return values.
📋 What You'll Learn
Create a reactive variable count with initial value 0
Create a composable function useCounter that returns count and an increment function
Add TypeScript types to the composable's return object
Use Vue 3 Composition API with ref and readonly
💡 Why This Matters
🌍 Real World
Typed composables help build reusable and safe logic blocks in Vue 3 apps, improving code quality and developer experience.
💼 Career
Understanding how to type composables is essential for Vue developers working with TypeScript in professional projects.
Progress0 / 4 steps
1
Setup a reactive count variable
Create a reactive variable called count using Vue's ref function and set its initial value to 0.
Vue
Hint

Use const count = ref(0) to create a reactive number starting at zero.

2
Create the useCounter composable function
Create a function called useCounter that returns an object with count and an increment function. The increment function should increase count.value by 1.
Vue
Hint

Define useCounter as a function that returns count and increment. The increment function adds 1 to count.value.

3
Add TypeScript types to the composable return
Add TypeScript types to the useCounter function so it returns an object with count typed as Ref<number> and increment typed as a function returning void. Import Ref from 'vue'.
Vue
Hint

Use Ref<number> to type count and () => void to type increment.

4
Make count readonly in the composable return
Import readonly from 'vue' and return count wrapped with readonly in the useCounter function to prevent external modification of count.
Vue
Hint

Use readonly(count) to protect count from outside changes.