联合类型

联合类型是一种灵活的数据类型,它修饰的变量可以存储不同类型的数据。
在这里插入图片描述

  • 语法:let 变量: 类型1 | 类型2 | 类型3 = 值

基于联合类型,变量可存不同类型数据

实例

// 需求:定义一个变量,存放【年终考试评价】
// 考试评价:可能是具体的分数,也可能是A、B、C、D等级
// let judge: number | string = 100
// judge = 'A+'
// judge = '优秀'
// judge = '不错,继续努力'
// console.log('年终考试评价', judge)

// 联合类型还可以将变量值,约定在一组数据范围内进行选择
// 性别:男 女 保密
let gender: 'man' | 'woman' | 'secret' = 'secret'
console.log(gender)
@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
  }
}

在这里插入图片描述

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐