HarmonyOS 如何判断联合类型的具体类型?

class Cat {
  // ...
}
class Dog {
  // ...
}
class Frog {
  // ...
}
type Animal = Cat | Dog | Frog | number
// Cat、Dog、Frog是一些类型(类或接口)

let animal: Animal = new Cat();

如何在代码运行时判断此animal为Cat类型

阅读 544
1 个回答

可以通过instanceof来判断实体类型

参考demo:

@Entry
@Component
struct TestPage1 {
  @State list: Array<Object> = [new Cat(), new Dog()]

  build() {
    Row() {
      Column() {
        ForEach(this.list, (item: Object) => {
          if (item instanceof Cat) {
            Text("this is Cat")
          } else if (item instanceof Dog) {
            Text("this is Dog")
          }
        })
      }.width('100%')
    }.height('100%')
  }
}

class Cat {
}

class Dog {
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进