TypeScript:类型“RegExpMatchArray”的参数无法分配给类型“string”的参数

7
我有以下表达式:
import { persistState } from 'redux-devtools';

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

我得到了一个关于匹配函数参数的错误,错误信息如下:

类型为 'RegExpMatchArray' 的参数不能分配给类型为 'string' 的参数。使用正则表达式匹配字符串,并返回包含搜索结果的数组。(方法) String.match(regexp: RegExp): RegExpMatchArray (+1 overload)

在VSCode中查看定义如下:
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.
  */

在我看来,该参数是一个正则表达式类型,并且在定义中也是如此。那么为什么会出现错误?


1
你用匹配结果做什么? - Nitzan Tomer
请提供一个MCVE - Tamas Hegedus
1个回答

4

@NitzanTomer是正确的。存在类型不匹配的问题并不在match函数的参数中。你肯定是尝试将match函数的返回值存储在一个字符串类型的变量中/从一个:string函数中返回它/将它作为string参数传递。


3
我认为这是VSCode智能感知的问题。只有匹配参数时才会出现下划线,而整个语句 window.location.href.match(/[?&]debug_session=([^&]+)\b/) 应该出现下划线。重启VSCode解决了这个问题。 - Kushagra Sharma
1
谢谢 @KushagraSharma,重新启动VSCode确实是我的解决办法。你有没有任何关于这个Bug是否已经报告的想法? - MaximeBernard
1
@MaximeBernard 我不知道是否已经报告了这个问题。 - Kushagra Sharma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接