Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

toJSON() on invalid dates produces null, although the type definition says that it always returns string #6202

Open
henhal opened this issue Jan 11, 2024 · 0 comments · May be fixed by #6221

Comments

@henhal
Copy link

henhal commented Jan 11, 2024

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

const m = moment(null);
const json = moment.toJSON();

assert(typeof json === 'string'); // fails

Expected behavior

The TS type definitions state that the moment() function accepts null as the input, which it does, but it produces a monent instance with an "Invalid date".
The TS type definitions also state that Moment.toJSON() returns string, but if the date is invalid, it will return null.

TS types must be trusted, that's kind of the point. I had correctly typed data (my input was typed string | undefined | null), and called moment(input).toJSON(), expecting to get a string back, but got null, which made my application crash.

Desktop (please complete the following information):

  • OS: Mac, Node.JS 18.x

Please run the following code in your environment and include the output:

> console.log((new Date()).toString())
Thu Jan 11 2024 12:12:12 GMT+0100 (Central European Standard Time)
undefined
> console.log((new Date()).toLocaleString())
1/11/2024, 12:12:12 PM
undefined
> console.log((new Date()).getTimezoneOffset())
-60
undefined
> console.log(navigator.userAgent)
Uncaught ReferenceError: navigator is not defined
> console.log(moment.version)
2.29.4

Additional context

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant