For my frontend app, I am utilizing React. The data I have contains two different time formats - one in the form of 08-10 and the other as 05:00-05:30. While most of the time format data follows the 08-10 structure, there are a few instances of 05:00-05:30.
Once I retrieve the time-date data, I use a map function to pass it to my time-format helper function. The desired display format in my browser is 05:00-05:30. Although my helper function functions correctly, the hurdle I face is a Typescript Error related to my regex expression. Specifically, it states Object is possibly 'null'
. Despite implementing conditions and optional chaining with ?
, the Typescript error persists. Resolving this Typescript issue eludes me.
The code I've shared can be accessed on codesandbox, where you can also observe the Typescript error.
import "./styles.css";
import React from "react";
const toFourDigitTime = (time: string) => {
if (time) {
const expression = /(\d{2}):?(\d{2})?/;
const [hours, minutes] = time?.match(expression).slice(1); // triggers a Typescript error
return `${hours.padStart(2, '0')}:${minutes ? minutes : '00'}`;
}
};
export const toTimeRangeFormat = (range: string): string | undefined => {
const [start, end] = range?.split('-');
if (start && end) {
return toFourDigitTime(start) + ' - ' + toFourDigitTime(end);
}
return range;
};
export default function App() {
const [state] = React.useState(["08-10", "05:00-05:30"]);
return (
<div className="App">
{state.map((i) => {
return (
<ul>
<li>{toTimeRangeFormat(i)}</li>
</ul>
);
})}
</div>
);
}