Performance: Typing composables
Typing composables affects the development experience and bundle size, indirectly influencing load speed and runtime performance.
import { ref, Ref } from 'vue'; export function useCounter(): { count: Ref<number>; increment: () => void } { const count = ref(0); function increment() { count.value++; } return { count, increment }; }
import { ref } from 'vue'; export function useCounter() { const count = ref(0); function increment() { count.value++; } return { count, increment }; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Untyped composable | 0 | 0 | 0 | [OK] Good for runtime but risky for dev |
| Typed composable | 0 | 0 | 0 | [OK] Good for dev experience, no runtime cost |
Ref<Type> to type reactive refs, so Ref<number> is correct for a number.count as Ref<number>. const count: reactive<number> = reactive(0); uses wrong syntax, C assigns ref to number type, D uses wrong type and string value.message inside the component?import { ref } from 'vue';
export function useMessage() {
const message = ref('Hello');
return { message };
}ref function returns a Ref object wrapping the value type, here a string.message is created by ref('Hello'), its type is Ref<string>.import { ref, Ref } from 'vue';
export function useCounter(): { count: Ref<number> } {
const count = ref('0');
return { count };
}count to be Ref<number>, but ref is called with a string '0'.title and a number count using Vue's Ref type?import { ref, Ref } from 'vue';
export function useData() {
const title = ref('My Title');
const count = ref(10);
return { title, count };
}title and count are refs holding string and number respectively, so their types are Ref<string> and Ref<number>.Ref<string> and Ref<number>.Pass the test and this pattern moves unknown