【鸿蒙学习笔记】数据类型

官方文档:ArkTS语言介绍

目录标题

代码总结

声明变量

cpp 复制代码
let hi: string = 'hello';
let hi2 = 'hello, world';    // 自动类型推断

声明常量

cpp 复制代码
const hello: string = 'hello';

数据类型 缺:byte char

Number类型 short int long float double

cpp 复制代码
let n1 = 3.14;
let n2 = 3.141592;
let n3 = .5;
let n4 = 1e10;

function factorial(n: number): number {
  if (n <= 1) {
    return 1;
  }
  return n * factorial(n - 1);
}

Boolean类型 boolean

cpp 复制代码
let isDone: boolean = false;

String类型

cpp 复制代码
let s1 = 'Hello, world!\n';       // 由单引号(')括起来
let s2 = "this is a string";      // 由双引号(")括起来
let s3 = `The result is ${a}`;    // 反向单引号(`)括起来的模板字面量

Void类型

void类型用于指定函数没有返回值。

Object类型

Object类型是所有引用类型的基类型。

Array类型

cpp 复制代码
let names: string[] = ['Alice', 'Bob', 'Carol'];

Enum类型

cpp 复制代码
enum ColorSet { Red, Green, Blue }
let c: ColorSet = ColorSet.Red;

enum ColorSet { White = 0xFF, Grey = 0x7F, Black = 0x00 }
let c: ColorSet = ColorSet.Black;

Union类型

cpp 复制代码
type Animal = Cat | Dog | Frog | number

let animal: Animal = new Cat();
animal = new Frog();
animal = 42;

let animal: Animal = new Frog();
if (animal instanceof Frog) {
  let frog: Frog = animal as Frog;
  animal.leap(); // 结果:青蛙跳
  frog.leap();   // 结果:青蛙跳
}
animal.sleep (); // 任何动物都可以睡觉

Aliases类型

Aliases类型为匿名类型(数组、函数、对象字面量或联合类型)提供名称,或为已有类型提供替代名称

cpp 复制代码
type Matrix = number[][];
type Handler = (s: string, no: number) => string;
type Predicate <T> = (x: T) => Boolean;
type NullableObject = Object | null;
相关推荐
梦想不只是梦与想1 小时前
鸿蒙 AI自动化测试实现
单元测试·harmonyos·hypium
代码山河3 小时前
Python就业方向全解析:后端、爬虫、数据分析、AI你选哪个?
python·学习·架构·教程·面向对象·项目
sbjdhjd3 小时前
网工进阶笔记:H3CSE 园区网全栈技术与协议汇总
网络·笔记·云计算·ssh·网络工程·vlan·aaa
释厄6233 小时前
AI学习层更新与跨体转移律——人类社会同构·不缺理解缺 U
人工智能·学习
海绵宝宝的月光宝盒7 小时前
14-AutoCAD-阵列命令应用与案例实战(AR)
经验分享·笔记·自动化·课程设计·制造·学习方法·cad
用户0934077735148 小时前
HarmonyOS WPS Open SDK 工程实践:把 registerApp 做成就绪门禁
typescript·harmonyos
小嘉丶学长8 小时前
Day14 · 字典与集合
java·开发语言·网络·python·学习·1024程序员节
白山编程大哥8 小时前
接口幂等性是什么?如何设计?
笔记
ACP广源盛139246256738 小时前
6 盘位存储扩展方案选型笔记:YLB3116 @ACP评估记录
笔记·硬件架构·硬件工程·国产芯片
小李不想当小白8 小时前
SPI通信外设与W25Q64 (硬件SPI)(STM32标准库学习笔记)
笔记·stm32·单片机·嵌入式硬件·学习·嵌入式