Blog>
Snippets

Type Checking with TypeScript

Illustrate how to integrate TypeScript into a Vue.js 3 project, including creating type-safe components and leveraging TypeScript's features for better code quality and maintainability.
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'MyComponent',
  props: {
    message: String
  },
  setup(props) {
    // The 'message' prop is typed as a string
    console.log(props.message.toUpperCase());

    return { //... };
  }
});
This is a simple Vue.js 3 component with TypeScript support. It uses the 'defineComponent' function from Vue.js, which enables type inference. The 'message' prop is specified as a string, and TypeScript will enforce this type.
import { ref, Ref } from 'vue';

export default defineComponent({
  setup() {
    const counter: Ref<number> = ref(0);

    function increment() {
      counter.value++;
    }

    return { counter, increment };
  }
});
In this Vue.js 3 component, TypeScript is used to define a reactive property 'counter' with a specific Ref<number> type, ensuring that 'counter' can only be a number. The 'increment' function updates the counter, and both 'counter' and 'increment' are returned from the 'setup' function to be used in the template.
import { computed, defineComponent, PropType } from 'vue';

export default defineComponent({
  name: 'MyTypedComponent',
  props: {
    initialCount: Number,
    title: {
      type: String as PropType<string>,
      required: true
    }
  },
  setup(props) {
    const count = ref(props.initialCount || 0);
    const doubleCount = computed(() => count.value * 2);

    return { count, doubleCount };
  }
});
This is an example of a typed Vue.js 3 component with more complex prop typing. The 'title' prop is required and of type string. The 'initialCount' prop is optional and of type number. A computed property 'doubleCount' is also defined, which will be reactive and type-safe, doubling the 'count' value.
import { createApp } from 'vue';
import MyTypedComponent from './components/MyTypedComponent.vue';

createApp(MyTypedComponent).mount('#app');
This is a simple TypeScript code snippet that shows how to integrate a typed Vue.js 3 component, 'MyTypedComponent', into the Vue application. It uses the 'createApp' function from Vue.js to create a new app instance with 'MyTypedComponent' as the root component, and then mounts it to the DOM element with the id 'app'.