typescript - 'string | 类型的参数 RegExp' 不可分配给“字符串”类型的参数
问题描述
我创建了一个接受pattern
arg 的函数,它可以是 astring
或 a RegExp
:
filePaths = findPathsDeep(`${__dirname}/test`, /Scene\d.md/)
function findPathsDeep(dir: string, pattern: string | RegExp) {
// This is where we store pattern matches of all files inside the directory
let results: string[] = []
// Read contents of directory
fs.readdirSync(dir).forEach((dirInner: string) => {
// Obtain absolute path
dirInner = path.resolve(dir, dirInner)
// Get stats to determine if path is a directory or a file
const stat = fs.statSync(dirInner)
// If path is a directory, scan it and combine results
if (stat.isDirectory()) {
results = results.concat(findPathsDeep(dirInner, pattern))
}
// If path is a file and ends with pattern then push it onto results
if (stat.isFile() && dirInner.endsWith(pattern)) {
results.push(dirInner)
}
})
return results
}
我认为or
使用错误?因为我收到了这个错误:
Argument of type 'string | RegExp' is not assignable to parameter of type 'string'.
Type 'RegExp' is not assignable to type 'string'.
106 if (stat.isFile() && dirInner.endsWith(pattern)) {
解决方案
您只能endsWith
使用字符串调用。
首先检查它是否是一个字符串:
if (stat.isFile()) {
if (typeof pattern === 'string') {
if (dirInner.endsWith(pattern)) {
results.push(dirInner)
}
} else if (pattern.test(dirInner)) {
results.push(dirInner)
}
}
对于正则表达式,您还需要传递一个$
以匹配行尾结尾的正则表达式 - 例如 pass /Scene\d\.md$/
。
请注意,要匹配文字句点,您必须使用\.
.
您还可以反编译正则表达式并在(?![\s\S])
其末尾添加 a 以匹配行尾,然后将其转换回正则表达式 - 但这要复杂得多。
(对于一般情况,您不能只添加 a$
因为$
可以匹配行的结尾,而不是字符串的结尾,如果m
正在使用标志 - 但如果您可以预期模式永远不会是多行的,$
将工作)
推荐阅读
- spring - 如何在 springboot jar 的 BOOT-INF/classes 中反映类
- linux - 嵌套 EPOLL FD
- javascript - 使用两列布局加载更多按钮
- wordpress - 无法从用户表 wordpress 中获取手机号码
- ios - 如何在imageView中对齐图像
- css - flexbox 和网格系统有什么区别?
- sql-server - SQL Server:如何在两次之间暂停计划作业?
- java - java.lang.ClassNotFoundException: com.lowagie.text.Font
- c# - ASP.NET Core 2 MVC + EF Core 2 或 Angular 5
- jenkins - 删除 Jenkins 中所有禁用的模块