Thursday, July 7, 2022

Extending built-in TypeScript objects in Vite

Checking whether an array is empty is a rather common operation. The usual way to do this in TypeScript is by checking the length property, but it’s very verbose:

if (myArray.length === 0) {
	// ...
}

For some reason, the JavaScript standard doesn’t specify an isEmpty() method. Fortunately, we can extend native JavaScript objects to add any methods we want. While this is a great feature, I was unable to make it work in a Vue + TypeScript + Vite project. I want the autocomplete of my VSCode to properly display it.

To make the TypeScript compiler recognize it, you must declare your method extensions as global by wrapping the declaration in a declare global block.

At first I tried to write the declaration in the “src/env.d.ts” file, but it didn’t work. Turns out you need to place them in a different file, as explained here. So I finally wrote them in a “src/extensions.d.ts” for the typings, and then the implementations themselves must be in a file that will be actually called in your application:

I tested the code above in a Vue project, but I believe it will work accordingly in a React project as well.

No comments: