Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JSDoc create and import type from another file

I have a user object returned by some function in user.model.js

const user = {
    id: "ASwsd122Wqwe1",
    name: "sam",
    email: "sam.joe@yahoo.uk",
    createdDate : 1721323231123
}

In another file, I’m returning this

const user = getUser();

How do i create a type for user?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use @typedef to create custom types, where @prop refers @property are properties in your object.

syntax : @typedef [<type>] <name>

In you user.model.js,

/**
 * @typedef {Object} user
 * @prop {string} id
 * @prop {string} name
 * @prop {string} email
 * @prop {number} createdDate
 */

// exports here

In another file, you can import the type like this

/** @typedef {import('./user.model.js').user} User */

/**@type {User} */
const user = getUser();

above globally defines the type

or

/**@type {import('./user.model.js').user} */
const user = getUser();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading