microsoft / microsoft/TypeScript
parseInt: use more concrete type for `radix` argument
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
Search Terms
parseInt, radix
Suggestion
From MDN docs:
radix: An integer between 2 and 36 that represents the radix
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Parameters
TS definition (lib.es5.d.ts):
declare function parseInt(s: string, radix?: number): number;
It will be safer to use more concrete type for radix:
type TRadix =
2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|32|33|34|35|36
function safeParseInt(s: string, radix?: TRadix) {
return parseInt(s, radix)
}
Use Cases
['1', '7', '11'].map(safeParseInt) // error -> Type 'number' is not assignable to type 'TRadix' ("strictFunctionTypes": true)
Examples
['1', '7', '11'].map(item) => safeParseInt(item, 10)) // OK
const config = {
nested: {
number: '42',
radix: 10,
},
} as const;
safeParseInt(config.nested.number, config.nested.radix)) // OK
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- 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, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
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 with the parseInt declaration in lib.es5.d.ts and review how its radix parameter is represented in the standard library definitions. Check the provided safeParseInt and map examples, then determine the type-level behavior and compatibility expectations that would define completion.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100