【问题标题】:Operator '*=' cannot be applied to types 'number | bigint' and 'number'.",运算符 '*=' 不能应用于类型 'number | bigint' 和 '数字'。",
【发布时间】:2021-05-15 19:42:26
【问题描述】:

我有来自js-combinatorics 的这个排列函数,我想配置它

const _BI = typeof BigInt == 'function' ? BigInt : Number;

const _crop = (n) => n <= Number.MAX_SAFE_INTEGER ? Number(n) : _BI(n);

function permutation(n, k) {
  if (n < 0)
      throw new RangeError(`negative n is not acceptable`);
  if (k < 0)
      throw new RangeError(`negative k is not acceptable`);
  if (0 == k)
      return 1;
  if (n < k)
      return 0;
  [n, k] = [_BI(n), _BI(k)];
  let p = _BI(1);
  while (k--) 
      p *= n--;
  return _crop(p);

}

ts 给我 p *= n--;

Operator '*=' cannot be applied to types 'number | bigint' and 'number'.

我该如何解决这个错误?

【问题讨论】:

    标签: typescript types


    【解决方案1】:

    这是| 运算符和*= 运算符的限制。

    1. *= 运算符不能对混合类型进行操作。您必须在两边输入相同的类型,或numberbigint
    2. 不过,如果你为np 都设置了一个通用模板N extends number|bigint,你也会遇到麻烦,因为n 可以是bigintnumberbigint|number(某种同时打字)。见https://github.com/microsoft/TypeScript/issues/39569

    【讨论】:

      猜你喜欢
      • 2023-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-28
      • 2022-11-12
      • 1970-01-01
      • 2020-04-28
      • 1970-01-01
      相关资源
      最近更新 更多