1

I have a function that uses moment.js. I am new to typescript and jsdoc imports and I'm wondering how I can document that a function returns, specifically a moment object:

const moment = require('moment-timezone');
/**
 * @typedef Moment
 * @property {import('moment-timezone').Moment} moment
 */

/**
 * Returns a moment object with the date / time converted to the given timezone
 * @param {Date} dateTime
 * @param {string} targetTimeZone
 * @return {Moment} 
 */
const convertDateTimeToLocationTimeZone = (dateTime, targetTimeZone) => {
    return moment(dateTime).tz(targetTimeZone);
};

I'm not even sure if the above is totally off - but also the above gives me this error in vscode:

Property 'moment' is missing in type 'import("/Users/Deb/Desktop/project/node_modules/moment/....").Moment' but required in type 'import("/Users/Deb/Desktop/project/...").Moment'.

Note, I do have @types/moment-timezone installed.

paul-shuvo
  • 1,874
  • 4
  • 33
  • 37
deblearns1
  • 103
  • 1
  • 10
  • 1
    What happens if you change the `typedef` line to this: `@typedef {import('moment-timezone').Moment} Moment `? ([source](https://stackoverflow.com/a/52847569/3015595)) – Joe Previte Dec 28 '19 at 04:00
  • No way! Hooray! I'll post it as a formal answer so that others will may benefit. – Joe Previte Dec 30 '19 at 14:53

1 Answers1

1

I think you almost have it. Based on this answer to a similar question, I think you need to modify your code to match this:

const moment = require('moment-timezone');
/**
 * @typedef {import('moment-timezone').Moment} Moment
 */

/**
 * Returns a moment object with the date / time converted to the given timezone
 * @param {Date} dateTime
 * @param {string} targetTimeZone
 * @return {Moment} 
 */
const convertDateTimeToLocationTimeZone = (dateTime, targetTimeZone) => {
    return moment(dateTime).tz(targetTimeZone);
};

Hope that works!

Joe Previte
  • 114
  • 1
  • 16