• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#  Type guarding is supported with ``instanceof`` and ``as``
2
3Rule ``arkts-no-is``
4
5**Severity: error**
6
7ArkTS does not support the ``is`` operator, which must be replaced by the
8``instanceof`` operator. Note that the fields of an object must be cast to the
9appropriate type with the ``as`` operator before use.
10
11
12## TypeScript
13
14
15```
16
17    class Foo {
18        foo: number = 0
19        common: string = ""
20    }
21
22    class Bar {
23        bar: number = 0
24        common: string = ""
25    }
26
27    function isFoo(arg: any): arg is Foo {
28        return arg.foo !== undefined
29    }
30
31    function doStuff(arg: Foo | Bar) {
32        if (isFoo(arg)) {
33            console.log(arg.foo)    // OK
34            console.log(arg.bar)    // Compile-time error
35        } else {
36            console.log(arg.foo)    // Compile-time error
37            console.log(arg.bar)    // OK
38        }
39    }
40
41    doStuff({ foo: 123, common: '123' })
42    doStuff({ bar: 123, common: '123' })
43
44```
45
46## ArkTS
47
48
49```
50
51    class Foo {
52        foo: number = 0
53        common: string = ""
54    }
55
56    class Bar {
57        bar: number = 0
58        common: string = ""
59    }
60
61    function isFoo(arg: Object): boolean {
62        return arg instanceof Foo
63    }
64
65    function doStuff(arg: Object): void {
66        if (isFoo(arg)) {
67            let fooArg = arg as Foo
68            console.log(fooArg.foo)     // OK
69            console.log(arg.bar)        // Compile-time error
70        } else {
71            let barArg = arg as Bar
72            console.log(arg.foo)        // Compile-time error
73            console.log(barArg.bar)     // OK
74        }
75    }
76
77    function main(): void {
78        doStuff(new Foo())
79        doStuff(new Bar())
80    }
81
82```
83
84
85