程序中有一个脚本,该脚本最终会调用一个接受字符串并在该字符串上运行.match(regex)
的函数。
根据MDN:String.prototype.match(regex)
返回一种array
数据类型,我只需要访问其第一个索引[0]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
在尝试重新组织此脚本的所有方式中,我都遇到了流错误:
“无法获得
findStationId(...)[0]
,因为在空[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页面,则会显示:
一个其内容取决于是否存在全局(g)标志的数组;如果找不到匹配项,则为null。
如果未找到匹配项,则为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
}