Typescript vue.js
Typescript vue.js

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.

What Is Extended Reality (XR) and How Is it Changing the World?
Post On December 06, 2023 | By Anna James

What Is Extended Reality (XR) and How Is it Changing the World?

Extended Reality (XR) is a fascinating realm where the digital and physical worlds converge, offering immersive experiences beyond our wildest imagination. It encompasses a spectrum of technologies, including Virtual Reality (VR), Augmented Reality (AR), and Mixed Reality (MR). In this article, we delve into the various dimensions of XR, exploring its types, evolution, advantages, applicationsRead more

Picking Your Career In XR: Designer Vs Developer Path
Post On December 06, 2023 | By Anna James

Picking Your Career In XR: Designer Vs Developer Path

In a world increasingly shaped by augmented reality (AR), virtual reality (VR), and mixed reality (MR), the demand for skills in AR and VR development and design is soaring. The career crossroads in the extended reality (XR) industry present aspiring professionals with a crucial decision: to delve into the intricacies of development or to embarkRead more

Immersive App Development With Extended Reality (XR)
Post On December 05, 2023 | By Anna James

Immersive App Development With Extended Reality (XR)

Understanding Extended Reality (XR) In the fast-paced digital landscape, Extended Reality (XR) emerges as a transformative force, encompassing virtual reality (VR), augmented reality (AR), and mixed reality (MR). XR presents a universal term, evolving continually and offering businesses new avenues for customer interaction. Embracing Virtual Reality (VR) Unveiling VR App Development Virtual Reality (VR) transcendsRead more

Brands we WORK with

2013 - 2023 Foreignerds Inc. All Rights Reserved

facebookFacebook
twitterTwitter
linkedinLinkedin
instagramInstagram