• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#  Unary operators ``+``, ``-`` and ``~`` work only on numbers
2
3Rule ``arkts-no-polymorphic-unops``
4
5**Severity: error**
6
7ArkTS allows unary operators to work on numeric types only. A compile-time
8error occurs if these operators are applied to a non-numeric type. Unlike in
9TypeScript, implicit casting of strings in this context is not supported and must
10be done explicitly.
11
12
13## TypeScript
14
15
16```
17
18    let a = +5        // 5 as number
19    let b = +"5"      // 5 as number
20    let c = -5        // -5 as number
21    let d = -"5"      // -5 as number
22    let e = ~5        // -6 as number
23    let f = ~"5"      // -6 as number
24    let g = +"string" // NaN as number
25
26    function returnTen(): string {
27        return "-10"
28    }
29
30    function returnString(): string {
31        return "string"
32    }
33
34    let x = +returnTen()    // -10 as number
35    let y = +returnString() // NaN
36
37```
38
39## ArkTS
40
41
42```
43
44    let a = +5        // 5 as number
45    let b = +"5"      // Compile-time error
46    let c = -5        // -5 as number
47    let d = -"5"      // Compile-time error
48    let e = ~5        // -6 as number
49    let f = ~"5"      // Compile-time error
50    let g = +"string" // Compile-time error
51
52    function returnTen(): string {
53        return "-10"
54    }
55
56    function returnString(): string {
57        return "string"
58    }
59
60    let x = +returnTen()    // Compile-time error
61    let y = +returnString() // Compile-time error
62
63```
64
65
66