【问题标题】:"Argument of type 'IArguments' is not assignable" error for arguments?参数的“'IArguments'类型的参数不可分配”错误?
【发布时间】:2020-11-14 17:10:46
【问题描述】:

我正在做一些 hacky 但非常必要的事情。我需要抑制某些实际上无害的控制台错误。

export const removeConsoleErrors = () => {
  const cloneConsoleError = console.error;

  const suppressedWarnings = [
    'Warning: React does not recognize the `%s` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `%s` instead. If you accidentally passed it from a parent component, remove it from the DOM element.%s',
    'Warning: Using the "className" prop on <View> is deprecated.', `View`.',
  ];

  console.error = function filterWarnings(msg: string) {
    if (!suppressedWarnings.some((entry) => msg.includes(entry))) {
      cloneConsoleError.apply(console, arguments);
    }
  };
};

这行得通,但我收到一个关于 `arguments: 的 TypeScript 错误:

“IArguments”类型的参数不能分配给“[any?, ...any[]]”类型的参数。 TS2345

我可以用这个修复错误,但它看起来很冗长。有没有更短的写法?

Const argumentsTyped: any = arguments;
cloneConsoleError.apply (console, argumentsTyped);

【问题讨论】:

    标签: typescript


    【解决方案1】:

    不再需要使用 arguments 魔术变量。您的代码可以很好地使用扩展语法:

    export const removeConsoleErrors = () => {
      const cloneConsoleError = console.error;
    
      const suppressedWarnings = [
        'Warning: React does not recognize the `%s` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `%s` instead. If you accidentally passed it from a parent component, remove it from the DOM element.%s',
        'Warning: Using the "className" prop on <View> is deprecated.', `View`
      ];
    
      console.error = function filterWarnings(...args) {
        const [msg] = args;
        if (!suppressedWarnings.some((entry) => msg.includes(entry))) {
          cloneConsoleError(...args);
        }
      };
    };
    

    【讨论】:

      猜你喜欢
      • 2021-09-10
      • 2016-06-17
      • 2018-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 2021-08-19
      • 1970-01-01
      相关资源
      最近更新 更多