Date.prototype.toJSON has incorrect return type
See original GitHub issueBug 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
.
Issue Analytics
- State:
- Created 2 years ago
- Comments:6 (3 by maintainers)
Top GitHub Comments
Unfortunately, there’s not a super clean, easy way to make a built-in type wider than it’s already declared 😕. This sort of thing makes me want to revisit the idea of having “strict” variants of lib files that people could opt into with the
lib
compiler option, so we could make these kind of changes without breaking the world.I guess the easiest option I would recommend is just writing a wrapper function around built-ins whose types are too loose, and always use your wrapper functions instead of the built-ins (you could enforce this with an ESLint rule):
Would be really nice to have correct return types in
toJSON()
andJSON.strigify()
. Today we run into a really bad bug on production because of this. I would expect that TS warned us. Sadly that was not the case. 😢