• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2021-2025 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16class A {
17    num: int = 41;
18}
19
20class B {
21    num: int = 42;
22}
23
24class C {
25    num: int = 43;
26    constructor(num: int) {
27        this.num = num;
28    }
29    num_to_return() : int {
30        return this.num;
31    }
32}
33
34function foo(x : A | B | C) {
35    if (x instanceof C) {
36        let xx = x as C;
37        assertEQ(xx.num_to_return(), 777, "Error! The num field of class `C` must be 777");
38    }
39    if (x instanceof A) {
40        assertTrue(false, "Error! x is instaceof C but not A");
41    }
42    assertEQ(x.num, 777, "Error! The num field of union must be 777");
43    let a: int = x.num + 3;
44    assertEQ(a, 780, "Error! Variable 'a' must be 780");
45    x.num += 223;
46    assertEQ(x.num, 1000, "Error! The num field of union must be 1000");
47}
48
49function main() {
50    let x : A | B | C;
51    x = new C(777);
52    foo(x);
53    assertEQ(x.num, 1000, "Error! The num field of union must be 1000");
54    if (x instanceof C) {
55        let xx = x as C;
56        assertEQ(xx.num_to_return(), 1000, "Error! The num field of class `C` must be 1000");
57    }
58    if (x instanceof B) {
59        assertTrue(false, "Error! x is instaceof C but not B");
60    }
61    x = new A();
62    assertEQ(x.num, 41, "Error! The num field of union must be 41");
63    x = new B();
64    assertEQ(x.num, 42, "Error! The num field of union must be 42");
65}
66
67