• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#  Indexed access is not supported for fields
2
3Rule ``arkts-no-props-by-index``
4
5**Severity: error**
6
7ArkTS does not support dynamic field declaration and access. Declare all
8object fields immediately in the class. Access only those class fields
9that are either declared in the class, or accessible via inheritance. Accessing
10any other fields is prohibited, and causes compile-time errors.
11
12To access a field, use ``obj.field`` syntax, indexed access (``obj["field"]``)
13is not supported. An exception are all typed arrays from the standard library
14(for example, ``Int32Array``), which support access to their elements through
15``container[index]`` syntax.
16
17
18## TypeScript
19
20
21```
22
23    class Point {
24        x: number = 0
25        y: number = 0
26    }
27    let p: Point = {x: 1, y: 2}
28    console.log(p["x"])
29
30    class Person {
31        name: string = ""
32        age: number = 0; // semicolon is required here
33        [key: string]: string | number
34    }
35
36    let person: Person = {
37        name: "John",
38        age: 30,
39        email: "***@example.com",
40        phoneNumber: "18*********",
41    }
42
43```
44
45## ArkTS
46
47
48```
49
50    class Point {
51        x: number = 0
52        y: number = 0
53    }
54    let p: Point = {x: 1, y: 2}
55    console.log(p.x)
56
57    class Person {
58        name: string
59        age: number
60        email: string
61        phoneNumber: string
62
63        constructor(name: string, age: number, email: string,
64                    phoneNumber: string) {
65            this.name = name
66            this.age = age
67            this.email = email
68            this.phoneNumber = phoneNumber
69        }
70    }
71
72    let person = new Person("John", 30, "***@example.com", "18*********")
73    console.log(person["name"])         // Compile-time error
74    console.log(person.unknownProperty) // Compile-time error
75
76    let arr = new Int32Array(1)
77    console.log(arr[0])
78
79```
80
81
82