Introduction
TypeScript helps catch mistakes early and makes your Vue code easier to understand and maintain.
TypeScript helps catch mistakes early and makes your Vue code easier to understand and maintain.
<script lang="ts" setup> import { ref } from 'vue' const count = ref<number>(0) function increment() { count.value++ } </script>
lang="ts" in the script tag to enable TypeScript in Vue components.number help Vue know what kind of data you expect.<script lang="ts" setup> const message: string = 'Hello Vue with TypeScript!' </script>
ref with a type to track reactive boolean state safely.<script lang="ts" setup> import { ref } from 'vue' const isVisible = ref<boolean>(true) </script>
ref.<script lang="ts" setup> import { ref } from 'vue' interface User { name: string age: number } const user = ref<User>({ name: 'Alice', age: 30 }) </script>
This Vue component uses TypeScript to keep track of a number count. The count starts at zero and increases when you click the button. TypeScript ensures count is always a number.
<script lang="ts" setup> import { ref } from 'vue' const count = ref<number>(0) function increment() { count.value++ } </script> <template> <button @click="increment">Clicked {{ count }} times</button> </template>
TypeScript works well with Vue's Composition API and <script setup> syntax.
Using TypeScript can slow down initial setup but helps prevent bugs later.
Editors like VS Code give better help when TypeScript is used.
TypeScript helps catch errors before running your Vue app.
It makes your code easier to read and maintain.
TypeScript works smoothly with Vue's modern features.
const props = defineProps<{ name: string }>() is the correct TypeScript way to type props in Vue 3's Composition API.props: { name: any } uses any, which loses type safety.const count = ref(0);
function increment() {
count.value += 1;
}
increment();
console.log(count.value);ref(0) creates a reactive number starting at 0. Access with count.value.increment() adds 1 to count.value, so it becomes 1. Then logging count.value outputs 1.const message = ref('Hello');
message = 'Hi';.value property. You cannot assign a string directly to the ref variable itself.message.value = 'Hi', not message = 'Hi'.const props = defineProps<{ value: string | number }>() tells TypeScript the prop can be string or number, enforcing type safety.props: defineProps<{ value: any }>() uses any, which disables type safety.Pass the test and this pattern moves unknown