• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#  Type inference in case of generic function calls is limited
2
3Rule ``arkts-no-inferred-generic-params``
4
5**Severity: error**
6
7ArkTS allows to omit generic type parameters if it is possible to infer
8the concrete types from the parameters passed to the function. A compile-time
9error occurs otherwise. In particular, inference of generic type parameters
10based only on function return types is prohibited.
11
12
13## TypeScript
14
15
16```
17
18    function choose<T>(x: T, y: T): T {
19        return Math.random() < 0.5 ? x : y
20    }
21
22    let x = choose(10, 20)   // OK, choose<number>(...) is inferred
23    let y = choose("10", 20) // Compile-time error
24
25    function greet<T>(): T {
26        return "Hello" as T
27    }
28    let z = greet() // Type of T is inferred as "unknown"
29
30```
31
32## ArkTS
33
34
35```
36
37    function choose<T>(x: T, y: T): T {
38        return Math.random() < 0.5 ? x : y
39    }
40
41    let x = choose(10, 20)   // OK, choose<number>(...) is inferred
42    let y = choose("10", 20) // Compile-time error
43
44    function greet<T>(): T {
45        return "Hello" as T
46    }
47    let z = greet<string>()
48
49```
50
51
52