microsoft / microsoft/TypeScript

Date.prototype.toJSON has incorrect return type

Open
#43,639 7 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

Bug Report

Date.prototype.toJSON() can return a string or null according to the spec https://tc39.es/ecma262/#sec-date.prototype.tolocaledatestring. For example new Date("").toJSON() returns null.

Currently, the return type of toJSON() is specified as a string:
https://github.com/microsoft/TypeScript/blob/131875bb849c0a9c56c26d09881453aace0cbfed/lib/lib.es5.d.ts#L879

🕗 Version & Regression Information

Typescript 4.2.3

💻 Code
new Date("").toJSON().slice(0,5);

produces an error at runtime since new Date("").toJSON() is null, but doesn't produce a typescript error because new Date("").toJSON() is assumed to be string.

🙂 Expected behavior

TypeScript should warn about the potentially null value when an arbitrary string is passed into Date. However, if the Date object can be guaranteed to be valid (for example new Date()), the return type of toJSON() should be string.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Read the declaration for Date.prototype.toJSON in lib/lib.es5.d.ts, then run the supplied example with an invalid Date and with new Date(). The issue is done when the TypeScript types warn about the potentially null result while preserving a string result when validity is guaranteed.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.