打字稿正则表达式对象可能是 'null'

Typescript Regex Object is possibly 'null'

我正在为我的前端应用程序使用 React。我有两种不同时间格式的数据。 一个是这样的08-10,另一个是这样的05:00-05:30。大多数时间格式数据是这样的08-10,很少是像05:00-05:30。 获取时间日期数据后,我使用地图函数并传递给我的时间格式辅助函数,在我的浏览器中,我想像这样显示我的数据 05:00-05:30。我的辅助函数按预期工作,但问题是我的正则表达式中出现 Typescript 错误。它说 Object is possibly 'null'. 我使用了条件和可选通道 ? 但仍然使用 Typescript。我不知道如何修复此 Typescript 错误。

我在 codesandbox 中分享了我的代码。您也可以在其中看到 Typescript 错误。

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>
  );
}

因为 match() returns 如果没有找到匹配则为 null。

你需要这样的东西

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