Will AI replace front end developers 2023 11 03T163650.167 5
Will AI replace front end developers 2023 11 03T163650.167 5

Exploring Vue 3’s Composition API and Strong Typing with TypeScript

Introduction

As a seasoned developer accustomed to working with React and TypeScript, my recent venture into contributing to a Vue application sparked an intriguing journey. Vue 3’s Composition API presented itself as a powerful alternative to the conventional Options API, resembling the familiar feel of React Hooks. In this exploration, I’ll delve into the nuances of the Options API versus the Composition API, shedding light on their differences and advantages.

Options API and Composition API Comparison

Understanding the evolution of Vue component creation is essential. The Options API, prevalent in Vue 2, provided a conventional approach, while the Composition API emerged as the new paradigm, emphasizing a more functional and composable structure. To illustrate this shift, consider a basic counter example implemented using the Options API:

vue
<!-- Options API Counter Component -->
<template>
<!-- Template Code -->
</template>
<script>
// JavaScript Code with Options API
export default {
// Component Configuration
props: { /* … */ },
data() { /* … */ },
computed: { /* … */ },
methods: { /* … */ }
}
</script>

In contrast, the Composition API streamlines the component’s logic, making it more concise and composable:

vue
<!-- Composition API Counter Component -->
<template>
<!-- Template Code -->
</template>
<script>
// JavaScript Code with Composition API
import { defineComponent } from “vue”;export default defineComponent({
// Component Configuration
props: { /* … */ },
setup() { /* … */ }
});
</script>

The Composition API’s declarative and functional nature enhances code readability and composability, akin to the benefits offered by React Hooks.

Strong Typing of Props in Vue

While both Options and Composition API support TypeScript integration, the process of strongly typing props differs significantly. Vue 2’s Options API, often criticized for its intricate type gymnastics, contrasts with the Composition API’s straightforward approach. In pursuit of enhancing type inference for objects and arrays, I embarked on a mission to implement strong typing of props in my Vue 3 codebase.

Defining Props with TypeScript

In Vue, defining props involves specifying their type using JavaScript prototypes. While this system covers various use cases, it falls short when dealing with vague types such as Object and Array. To address this, I sought to utilize more complex TypeScript types to provide clarity and precision.

typescript
defineProps({
user: {
type: Object as PropType<UserType>,
required: true,
},
comments: {
type: Array as PropType<CommentType[]>,
required: true,
},
notifications: {
type: Number,
default: 0,
}
});

This approach enables the use of advanced TypeScript features, including unions, generics, and other language capabilities to compose intricate types, resulting in more robust and maintainable code.

Enabling TypeScript Support in Vue 3

Integrating TypeScript into a Vue 3 project, particularly when using Vite for compilation, is a seamless process. The creation of a tsconfig.json file, leveraging existing Vue and Vite configurations, facilitates the incorporation of TypeScript without a significant footprint.

json
{
"extends": "@vue/tsconfig/tsconfig.web.json",
"compilerOptions": { /* ... */ },
"include": ["src/**/*.vue", "src/**/*.ts"]
}

This streamlined setup allows for the seamless adoption of TypeScript, empowering developers to harness its benefits without compromising on build speed.

Defining Custom TypeScript Types

In scenarios where the codebase lacks a declarative source, as in the case of a Laravel codebase with Inertia, manually declaring TypeScript types becomes necessary. Crafting custom types for entities such as Paginated<T> and UserType ensures a tailored and precise representation of the data structure.

typescript
interface Paginated<T> { /* ... */ }
interface CommonUserAttributes { /* ... */ }
interface UserType extends CommonUserAttributes { /* ... */ }

These custom types serve as the foundation for strongly typed props, enhancing the clarity and maintainability of the codebase.

Build Time vs. Live Type Checking

A crucial consideration when working with TypeScript in a Vue 3 project is the distinction between build time and live type checking. Vite, leveraging Rollup and Babel, introduces a unique approach wherein TypeScript code undergoes compilation via Babel’s TypeScript preset. This implies that the TypeScript compiler does not directly analyze the code.

To bridge this gap, incorporating a plugin into Vite enables type checking during compilation. However, this approach introduces trade-offs, as it may impact compilation speed and hinder development agility. Striking a balance between build time and live type checking is essential, with the possibility of selectively enabling type checking based on development needs.

javascript
// Vite Configuration with Type Checking
import { defineConfig } from "vite";
import checker from "vite-plugin-checker";
export default defineConfig({
// [Rest of the config]
plugins: [
// [My other plugins]
checker({ vueTsc: true })
],
});

By adopting a build-time type checking strategy, developers can maintain a favorable development pace while ensuring the overall type safety of the codebase.

Final Thoughts

As this journey unfolds, the integration of Vue 3’s Composition API with TypeScript proves to be a transformative experience. The Composition API’s functional and composable nature, coupled with strong typing of props, elevates the development experience. Balancing the advantages of TypeScript with the efficiency of Vite requires thoughtful configuration and consideration of the development workflow. As I continue to implement and refine these practices, the benefits in terms of code quality and maintainability are becoming increasingly evident. Embracing the power of Vue 3 and TypeScript opens new avenues for creating robust and scalable applications.

© 2013 - 2024 Foreignerds. All Rights Reserved

facebookFacebook
twitterTwitter
linkedinLinkedin
instagramInstagram
whatsapp
support