Typing composables helps you catch mistakes early and understand your code better by telling Vue what kind of data your composable works with.
0
0
Typing composables in Vue
Introduction
When you create reusable logic in Vue using composables and want to ensure the data types are correct.
When you want your code editor to give helpful hints and catch errors while writing Vue composables.
When sharing composables with others to make it clear what inputs and outputs are expected.
When working on larger Vue projects where clear data types improve maintainability.
Syntax
Vue
import { ref, Ref } from 'vue' function useCounter(): { count: Ref<number>, increment: () => void } { const count = ref(0) function increment() { count.value++ } return { count, increment } }
Use TypeScript to add types to your composable function's inputs and outputs.
Use Vue's Ref type to type reactive references.
Examples
This composable manages a string message with proper typing for the reactive ref and the setter function.
Vue
import { ref, Ref } from 'vue' function useMessage(): { message: Ref<string>, setMessage: (newMsg: string) => void } { const message = ref('Hello') function setMessage(newMsg: string) { message.value = newMsg } return { message, setMessage } }
This composable toggles a boolean state with typed input and output.
Vue
import { ref, Ref } from 'vue' function useToggle(initial: boolean = false): { state: Ref<boolean>, toggle: () => void } { const state = ref(initial) function toggle() { state.value = !state.value } return { state, toggle } }
Sample Program
This example shows a typed composable useCounter that returns a number ref and an increment function. We use it and print the count before and after incrementing.
Vue
import { ref, Ref } from 'vue' // Composable to manage a number counter function useCounter(): { count: Ref<number>, increment: () => void } { const count = ref(0) function increment() { count.value++ } return { count, increment } } // Using the composable const { count, increment } = useCounter() console.log(count.value) // 0 increment() console.log(count.value) // 1
OutputSuccess
Important Notes
Always import Vue types like Ref when typing reactive variables.
Typing composables improves code safety and editor support.
You can also type parameters your composable accepts for more flexibility.
Summary
Typing composables means adding TypeScript types to your Vue composable functions.
This helps catch errors and makes your code easier to understand.
Use Vue's Ref type for reactive data inside composables.