javascript - string.match() 的流类型问题

标签 javascript flowtype

我的程序中有一个脚本,最终调用一个接受字符串并对该字符串运行 .match(regex) 的函数。


根据 MDN:
String.prototype.match(regex) 返回一个 array 数据类型,我只需要访问其中的第一个索引 [0]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match



我尝试以各种方式重新组织此脚本,但都遇到了流程错误:

"Cannot get findStationId(...)[0] because an index signature declaring the expected key / value type is missing in null [1]."

函数的组织不是我遇到问题的地方,而是 [0] 索引引用的问题。



如何正确键入检查并声明预期值?

// @flow

type RssResults = Array<{
  title: string,
  contentSnippet: string
}>

const findStationId = (string: string): Array<any> | null => string.match(/([0-9]{5}|[A-Z\d]{5})/)

export default (rssResults: RssResults) => {
  const entries = []
  rssResults.forEach((entry) => {
    const observation = {}
    observation.title = entry.title
    const id = findStationId(entry.title)[0] // flow errors here on [0]
    observation.id = id.toLowerCase()

    // ...        

    entries.push(observation)
  })
return entries
}


.flowconfig

[ignore]
.*/test/*

[include]

[libs]

[lints]

[options]
module.file_ext=.js
module.file_ext=.jsx
module.file_ext=.json
module.file_ext=.css
module.file_ext=.scss
module.name_mapper.extension='css' -> 'empty/object'
module.name_mapper.extension='scss' -> 'empty/object'

[strict]

[untyped]
.*/node_modules/**/.*

谢谢!

最佳答案

如果您仔细查看该 MDN 页面,会发现:

An Array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found.

“如果未找到匹配项,则为 null”。是这里的关键部分。 null[0]没有意义。您自己的返回类型 Array<any> | null还提到了这一点。

所以要么你的

const id = findStationId(entry.title)[0]

应该做

const match = findStationId(entry.title)
if (!match) throw new Error("No station ID found")
const id = match[0]

或者你应该改变 findStationId不允许 null返回。

const findStationId = (string: string): Array<any> => {
  const match = string.match(/([0-9]{5}|[A-Z\d]{5})/)
  if (!match) throw new Error("No station ID found")
  return match
}

关于javascript - string.match() 的流类型问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58089544/

相关文章:

javascript - 如何使用 AS3 运行 jQuery 函数

javascript - 输入类型 ="date"的值以相反方向显示

react-router - 流 : react-router. 未找到所需模块

javascript - 深度子类型的流错误

typescript - 在 Flow 中导入 TypeScript 模块

flowtype - Flow 需要很长时间才能启动,因为它会检查 node_modules

javascript - Flow 给我 React Native 类型定义/代码的错误

javascript - AngularJS Factory 在每次点击时加载数据

javascript - PHP - Jquery,在每行下方显示快速详细信息 slider

javascript - ActiveXObject ("WScript.Shell");在 Firefox 中未定义?