《鸿蒙第一行代码》第三课 断言的学习

47 阅读1分钟
《鸿蒙第一行代码》第三课 断言的学习

先说总结:

  • 1.联合类型可以被断言为其中一个类型
  • 2.父类可以被断言为子类
  • 3.任何类型都可以被断言为 any
  • 4.any 可以被断言为任何类型
  • 5.要使得 A 能够被断言为 B,只需要 A 兼容 B 或 B 兼容 A 即可 其实前四种情况都是最后一个的特例。

用的时候:类型声明是比类型断言更加严格的 所以为了增加代码的质量,我们最好优先使用类型声明,这也比类型断言的 as 语法更加优雅

简单示例代码:

export  interface Animal {
  name: string;
}
export  class  Cat {
  name: string = '';
  age: string = '';
}
const animal: Animal = {
  name: 'tom'
};

const  cat1: Cat = {
  name: 'cat1',
  age:'aa'
};


@Entry
@Component
struct Assertion_Page {
  @State message: string = 'Hello World'



  aboutToAppear(){
    // instanceof 后需要的是一个真正的class类型
    // instanceof操作符在TypeScript中只能用于检查对象是否是某个类的实例,而不能用于检查对象是否符合某个接口的形状
    // Cat是个类
    if (animal instanceof Cat) {


    }
    let tom :Cat = animal as Cat;


    // let tom1 :Animal = cat as Animal;
    // tom1.name
  }

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
  }
}
《鸿蒙第一行代码》项目代码结构图:

在这里插入图片描述
有需要《鸿蒙第一行代码项目源码》的私信我,我每天都看私信的