我的程序中有一个脚本,最终调用一个接受字符串并对该字符串运行 .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/