'string | 类型的参数RegExp' 不可分配给类型为 'string'

时间:2021-03-18 15:39:14

标签: typescript function types

我创建了一个接受 pattern 参数的函数,参数可以是 stringRegExp

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)) {

1 个答案:

答案 0 :(得分:3)

您只能使用字符串调用 endsWith

首先检查它是否是一个字符串:

if (stat.isFile()) {
    if (typeof pattern === 'string') {
        if (dirInner.endsWith(pattern)) {
            results.push(dirInner)
        }
    } else if (pattern.test(dirInner)) {
        results.push(dirInner)
    }
}

对于正则表达式,您还需要传递以 $ 结尾的正则表达式以匹配行尾 - 例如传递 /Scene\d\.md$/

请注意,要匹配文字句点,您必须使用 \. 对其进行转义。

您也可以反编译正则表达式并在其末尾添加 (?![\s\S]) 以匹配行的末尾,然后将其转回正则表达式 - 但这要复杂得多。< /p>

(对于一般情况,您不能只添加 $,因为 $ 可以匹配 的结尾,而不是 的结尾>string,如果正在使用 m 标志 - 但如果您可以期望模式永远不会是多行的,那么 $ 将起作用)