运算符'+'不能应用于类型'number []':如何纠正构建错误?

Ama*_*nda 1 javascript typescript

以下函数生成uuidv4字符串。

function uuidv4() {
  return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
    (
      c ^
      (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
    ).toString(16)
  );
}
console.log(uuidv4());
Run Code Online (Sandbox Code Playgroud)

使用打字稿时,当我尝试构建时,出现错误消息:

TS2365: Operator '+' cannot be applied to types 'number[]' and '-1000'.
Run Code Online (Sandbox Code Playgroud)

如何使用打字稿成功构建相同的功能?

Cer*_*nce 6

这是一种缩小技术。在那计算整个表达式(([1e7] + -1e3 + -4e3 + -8e3 + -1e11)),然后得到字符串

10000000-1000-4000-8000-100000000000
Run Code Online (Sandbox Code Playgroud)

因此,只需使用它,而不是依靠强制(Typescript不满意):

10000000-1000-4000-8000-100000000000
Run Code Online (Sandbox Code Playgroud)

此时,您也可以将所有非四(一)替换为零,如果需要的话,它们现在没有任何作用。