首页 > 解决方案 > 'string | 类型的参数 RegExp' 不可分配给“字符串”类型的参数

问题描述

我创建了一个接受patternarg 的函数,它可以是 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)) {

标签: typescriptfunctiontypes

解决方案


您只能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正在使用标志 - 但如果您可以预期模式永远不会是多行的,$将工作)


推荐阅读