Writing Type-Safe Composables in Vue 3
What Are Composables?
Composables are the Vue 3 answer to React hooks — reusable functions that encapsulate reactive state and logic. With TypeScript, they become even more powerful.
Generics for Flexibility
Use TypeScript generics to write composables that adapt to any data shape:
function useAsync<T>(fn: () => Promise<T>) {
const data = ref<T | null>(null);
const error = ref<Error | null>(null);
// ...
}Best Practices
Always return plain refs (not reactive objects) for destructuring support. Name your composables with the use prefix. Keep side effects in onMounted or watchEffect.
Comments (0)