简体   繁体   中英

Typescript Regex Object is possibly 'null'

I am using React for my frontend app. I have two different time format of data. One is like this 08-10 and another one is like this 05:00-05:30. Most of the time format data is like this 08-10, few are like 05:00-05:30. After getting the time date data, I used map function and pass to my time-format helper function, In my browser I want to display my data like this 05:00-05:30. My helper function works as expected but The problem is I am Typescript Error in my regex expression. It says Object is possibly 'null'. I used condition and as well optional-channing ? but still getting Typescript. I don't know how to fix this Typescript error.

I shared my code in codesandbox . You can see the Typescript error in there too.

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); // throws me 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>
  );
}

Because match() returns null if no matches are found.

You need something like

const m = time.match(expression);
if (m) {
  const [hours, minutes] = m.split(1);
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM