A computed property is a special reactive value that automatically updates when its dependencies change. It caches the result until dependencies change again.
Click to reveal answer
beginner
Why do we type computed properties in Vue with TypeScript?
Typing computed properties helps catch errors early, provides better code completion, and ensures the computed value has the expected type.
Click to reveal answer
intermediate
How do you type a computed property that returns a string in Vue 3 with TypeScript?
Use the generic type parameter: const myComputed = computed<string>(() => { return 'hello'; });
Click to reveal answer
intermediate
What happens if you don't type a computed property explicitly in Vue with TypeScript?
TypeScript will infer the type from the return value, but explicit typing improves clarity and helps avoid mistakes when the return type is complex.
Click to reveal answer
beginner
Show a simple example of typing a computed property that returns a number in Vue 3.
A. The computed function should not use an arrow function.
B. The ref should be typed as string, not number.
C. The computed type should be number, not string.
D. The computed property cannot depend on a ref.
Solution
Step 1: Check the computed return value type
The expression count.value * 2 results in a number.
Step 2: Match computed generic type
The computed is typed as string, which mismatches the number result.
Final Answer:
The computed type should be number, not string. -> Option C
Quick Check:
Computed type must match return value type [OK]
Hint: Match computed generic type to returned value type [OK]
Common Mistakes:
Typing computed as string when returning number
Thinking arrow functions are invalid in computed
Believing computed can't depend on refs
5. You want to create a typed computed property that returns the count of items in a reactive array items. Which is the correct way to type it in Vue 3 with TypeScript?