Typescript: Operator '+' cannot be applied to types 'number[]' and '-1000'

Created on 12 Sep 2017  ·  1Comment  ·  Source: microsoft/TypeScript

Got a function from here:
https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
And TS says there is an error, not sure if it is true.
And in case this is not an error, but ts does count this as error - is there any way to @suppress it?
Thanks.

TypeScript Version: 2.3.2 / but same in playground: https://www.typescriptlang.org/play/index.html

Code

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

Expected behavior:
No error?
Actual behavior:
Operator '+' cannot be applied to types 'number[]' and '-1000'.

Question

Most helpful comment

This is not a support forum.

Questions should be asked at StackOverflow or on Gitter.im.

But... TypeScript is protecting you from implicit coercion, so you need to cast the array literal:

  function uuidv4()
  {
-    return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
+    return ([1e7] as any + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
      (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
    )
  }

>All comments

This is not a support forum.

Questions should be asked at StackOverflow or on Gitter.im.

But... TypeScript is protecting you from implicit coercion, so you need to cast the array literal:

  function uuidv4()
  {
-    return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
+    return ([1e7] as any + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
      (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
    )
  }
Was this page helpful?
0 / 5 - 0 ratings