microsoft / microsoft/TypeScript
Narrow unnecessarily ambiguous Date.getMonth return type.
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
The specified behaviour of Date.getMonth implies that it will always return a number from 0 - 11 inclusive.
Hence annotating the return type (source) as number is unnecessarily ambiguous.
If it would be accepted, I would like to open a PR to narrow the type down to the 12 values from 0 - 11.
🔍 Search Terms
Date
getMonth
ambiguous type
narrowing type
✅ Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- the set of
0..11inclusive is also part of the setnumber. Hence this narrowing is not breaking.
- the set of
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
⭐ Suggestion
If it would be accepted, I would like to open a PR to narrow the type down to the 12 values from 0 - 11.
interface Date {
getMonth(): 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11
}
📃 Motivating Example
I think this is a very small and self-explanatory enhancement. The benefit here being that the type better describes the behaviour.
Whereas before "the set of things this function could do" was much wider. Now by reading the type (even if you didn't know the name of the method) you could rest assured that you are handling all cases correctly.
Secondly, by looking at the type, one need not read documentation to know that January is 0, not 1 as many JS developers probably learned the hard way.
💻 Use Cases
Make types represent the behaviour of a function more accurately.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start in lib/lib.es5.d.ts around line 751, where the Date.getMonth declaration is linked. Compare the declared return type with the stated 0–11 behavior and review the issue's proposed literal-union type. Done means the declaration accurately reflects all possible month values and the relevant TypeScript checks pass.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100