Velo By Wix: Global type definitions
How to add a global JSDoc types definition in Velo
In one of my previous posts, Type safety your code with JSDoc, we considered how to use the type definitions and JSDoc annotations in Velo. In this post, I want to show how we can use global types in Velo editor.
Global type definitions file
In Velo, we also are able to use global types annotations. The global types will be available on any JS/JSW files on the editor. It could be helpful if you use the same entity in separate files.
To declare global types in Velo, we should create a *.d.js
file in the public section. For example, I always use types.d.js
file. The end of the file with .d.js
is required.
Use tag @typedef
, we describe types.
We can use JSDoc syntax or TypeScript syntax inside JSDoc.
Use case examples
For example, we want to send a user data object to the lightbox when it opens. And use this data in the lightbox. Using global typedef, we can share types info across a page tab and lightbox page tab.
My user object will have three properties:
Example of User Data Object
{
"memeberId": "3bbf4e2c-528d-4b90-a882-cd80641687fc",
"nickname": "Bob",
"email": "bob@email.ua"
}
Let's start with types annotation. I prefer to use a TypeScript object types syntax for object definitions. It's similar to CSS syntax, where we describe a key name and types inside curly braces separate with semicolons @typedef { { keyName: type; … } } TypeName
public/types.d.js
// Filename: public/types.d.js
/**
* @typedef {{
* memeberId: string;
* nickname: string;
* email: string;
* }} TUser
*/
Now, the TUser
type is available globally on the project. In the Page Code Tab, we apply the TUser
type for creating a user object.
Page Code Tab
import { openLightbox } from 'wix-window';
import { currentMember } from 'wix-members';
$w.onReady(function () {
$w('#button1').onClick(async () => {
const memeber = await currentMember.getMember();
/** @type {TUser} */
const user = {
memeberId: memeber._id,
nickname: memeber.profile.nickname,
email: memeber.loginEmail,
};
openLightbox('Confirm-Lightbox', user);
});
});
You can ensure that the editor starts to work with autocomplete and code analysis if we use types.
Also, we should use the TUser
type for annotation of lightbox context data. It starts to work with autocomplete and code analysis too.
Lightbox Page Code Tab
import { lightbox } from 'wix-window';
$w.onReady(function () {
/** @type {TUser} */
const user = lightbox.getContext();
$w('#text1').text = user.nickname;
$w('#text2').text = user.email;
});
Typed code provides a good developer experience. It's helpful for automatization your development process. You don't need to keep in mind the data structure. And auto types analysis improves your code safety.
Resources
- Official documentation for JSDoc 3
- TypeScript: Documentation - JSDoc Reference
- JSDoc Cheatsheet and Type Safety Tricks