JSDoc create and import type from another file

42 views Asked by At

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

const user = {
    id: "ASwsd122Wqwe1",
    name: "sam",
    email: "[email protected]",
    createdDate : 1721323231123
}

In another file, I'm returning this

const user = getUser();

How do i create a type for user?

1

There are 1 answers

0
Yuvaraj M On

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();