Looking to develop a function that can handle duration strings like 12ms
, 7.5 MIN
, or 400H
, and then convert them into milliseconds.
const units = {
MS: 1,
S: 1 * 1000,
MIN: 60 * 1 * 1000,
H: 60 * 60 * 1 * 1000
}
export function toMS(str: string): number {
let regex = /^(?<number>\d+(?:\.\d+)?)(?:\s*(?<unit>MS|S|MIN|H))?$/i
if (!regex.test(str)) {
throw new TypeError(`Expected a duration, got: ${str}`)
}
let match = str.match(regex)
let number = Number(match?.groups?.number)
let unit = (match?.groups?.unit || 'ms').toUpperCase()
return Math.floor(number * units[unit])
}
The function toMS()
validates the provided string format (number
+ optional whitespace
+ optional unit abbreviation
) before parsing it with str.match(regex)
.
All is well until reaching units[unit]
, which triggers an error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type
.
Prior encounters with this type of error were resolved by enforcing types for function arguments and class constructors, but in this case where user input varies, finding a solution remains elusive. Forcing str.match(regex).groups.unit
to conform to specific types such as : 'MS | S | MIN | H'
seems unattainable.
While one route could involve creating an tsconfig.json file with "noImplicitAny": false
, such an approach may not align with the current project requirements.