Vue3 Fundamentals ยท Vue 3 + TypeScript

Typed refs

Typed refs

A ref holds a value, and in a <script setup lang="ts"> block Vue infers the value's type from what you pass in. ref(0) becomes a Ref<number>, so every read and write of count.value is checked against number.

Inference only goes so far. When the initial value does not make the type obvious, annotate the ref with the type you mean:

<script setup lang="ts">
import { ref } from 'vue';

const count = ref<number>(0);
const tags = ref<string[]>([]);
</script>

The annotation is the source of truth. count.value is a number, so assigning a string is a compile error rather than a bug you find at run time.

That matters because the wrong type changes what the code does. Seed the same counter with a string, ref('0'), and count.value + 1 joins the two values into '01' instead of adding them. The type was wrong, so the arithmetic was wrong.

In App.vue, hold the count in a ref<number> so adding one adds.

Challenge

The counter is stored as text, so adding one joins the strings instead of adding them. Export an App component from App.vue that holds the count in a ref<number> and renders count + 1 inside a <p>.

The Test mounts your component and reads the paragraph. The starter seeds the ref with '0', so the paragraph reads 01 and the Test fails. Annotate the ref as ref<number>(0) so the addition produces 1.

App.vue
<script setup lang="ts">
import { ref } from 'vue';

const count = ref('0');
</script>

<template>
  <p>{{ count + 1 }}</p>
</template>

No test run yet

The Test is hidden. Run it to check the Challenge โ€” you only see the result, never the test source.