Typescript:“RegExpMatchArray”类型的参数不可分配给“string”类型的参数

Kus*_*rma 7 typescript visual-studio-code typescript1.8 typescript-typings

我有以下表达:

import { persistState } from 'redux-devtools';

const enhancer = compose(
  applyMiddleware(thunk, router, logger),
  DevTools.instrument(),
  persistState(
    window.location.href.match(/[?&]debug_session=([^&]+)\b/)
  )
);
Run Code Online (Sandbox Code Playgroud)

我对匹配函数的参数感到困惑,并出现以下错误

“RegExpMatchArray”类型的参数不可分配给“string”类型的参数。将字符串与正则表达式进行匹配,并返回包含该搜索结果的数组。(方法) String.match(regexp: RegExp): RegExpMatchArray (+1 重载)

VSCode 中的 peek 定义显示:

match(regexp: string): RegExpMatchArray;
/**
  * Matches a string with a regular expression, and returns an array containing the results of that search.
  * @param regexp A regular expression object that contains the regular expression pattern and applicable flags.
  */
match(regexp: RegExp): RegExpMatchArray;

/**
  * Replaces text in a string, using a regular expression or search string.
  * @param searchValue A string that represents the regular expression.
  * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.
  */
Run Code Online (Sandbox Code Playgroud)

在我看来,参数的类型是 RegExp,定义中的参数也是类型。那为什么会报错呢?

Tam*_*dus 4

@NitzanTomer 是对的。类型不匹配的不是匹配函数参数。您当然会尝试将 match 函数的返回值存储在字符串类型变量中/从函数返回它:string/将其作为string参数传递。

  • 我认为这是 VSCode 智能感知的问题。摇摆仅在要匹配的参数上,而整个语句 `window.location.href.match(/[?&]debug_session=([^&]+)\b/)` 应该具有摇摆。重新启动 VSCode 修复了它。 (3认同)