[英]Typescript Regex Object is possibly 'null'
我正在为我的前端应用程序使用 React。 我有两种不同时间格式的数据。 一个是这样的 08-10,另一个是这样的 05:00-05:30。 大多数时间格式数据是08-10这样,很少是05:00-05:30这样。 获取时间日期数据后,我使用 map function 并传递给我的时间格式助手 function,在我的浏览器中我想显示我的数据:300:00 像这样。 我的助手 function 按预期工作,但问题是我是 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() 将返回 null。
你需要类似的东西
const m = time.match(expression);
if (m) {
const [hours, minutes] = m.split(1);
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.