简体   繁体   English

Typescript 正则表达式 Object 可能是“空”

[英]Typescript Regex Object is possibly 'null'

I am using React for my frontend app.我正在为我的前端应用程序使用 React。 I have two different time format of data.我有两种不同时间格式的数据。 One is like this 08-10 and another one is like this 05:00-05:30.一个是这样的 08-10,另一个是这样的 05:00-05:30。 Most of the time format data is like this 08-10, few are like 05:00-05:30.大多数时间格式数据是08-10这样,很少是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.获取时间日期数据后,我使用 map function 并传递给我的时间格式助手 function,在我的浏览器中我想显示我的数据:300:00 像这样。 My helper function works as expected but The problem is I am Typescript Error in my regex expression.我的助手 function 按预期工作,但问题是我是 Typescript 在我的正则表达式中出错。 It says Object is possibly 'null'.它说Object is possibly 'null'. I used condition and as well optional-channing ?我使用了条件和可选通道? but still getting Typescript.但仍然得到 Typescript。 I don't know how to fix this Typescript error.我不知道如何修复这个 Typescript 错误。

I shared my code in codesandbox .我在codesandbox中分享了我的代码。 You can see the Typescript error in there too.您也可以在那里看到 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>
  );
}

Because match() returns null if no matches are found.因为如果没有找到匹配项,match() 将返回 null。

You need something like你需要类似的东西

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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