• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2024 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 Foo {
17    foo: number = 0
18    common: string = ""
19}
20
21class Bar {
22    bar: number = 0
23    common: string = ""
24}
25
26function isFoo(arg: any): arg is Foo {
27    return arg.foo !== undefined
28}
29
30function doStuff(arg: Foo | Bar) {
31    if (isFoo(arg)) {
32        console.log(arg.foo)    // OK
33        console.log(arg.bar)    // Compile-time error
34    } else {
35        console.log(arg.foo)    // Compile-time error
36        console.log(arg.bar)    // OK
37    }
38}
39
40doStuff({ foo: 123, common: '123' })
41doStuff({ bar: 123, common: '123' })
42
43
44function isFoo2(arg: Object): boolean {
45    return arg instanceof Foo
46}
47
48function doStuff2(arg: Object): void {
49    if (isFoo2(arg)) {
50        let fooArg = arg as Foo
51        console.log(fooArg.foo)     // OK
52        console.log(arg.bar)        // Compile-time error
53    } else {
54        let barArg = arg as Bar
55        console.log(arg.foo)        // Compile-time error
56        console.log(barArg.bar)     // OK
57    }
58}
59
60function main(): void {
61    doStuff2(new Foo())
62    doStuff2(new Bar())
63}