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

官方文档: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;
相关推荐
xuhaoyu_cpp_java1 小时前
项目学习(三)分页查询
java·经验分享·笔记·学习
小宋加油啊3 小时前
机械臂抓取物体 PVN3D算法调研学习
学习·算法·3d
Xzh04234 小时前
AI Agent 学习路线(Java 后端方向)
java·人工智能·学习
Cloud_Shy6184 小时前
解读《Effective Python 3rd Edition》:从练气到老魔(第五章 Item 33 - 35)
开发语言·人工智能·笔记·python·学习方法
做cv的小昊4 小时前
计算机图形学:【Games101】学习笔记08——光线追踪(辐射度量学、渲染方程与全局光照、蒙特卡洛积分与路径追踪)
图像处理·笔记·学习·计算机视觉·游戏引擎·图形渲染·概率论
星恒随风4 小时前
C++ 类和对象入门(五):初始化列表、explicit 和 static 成员详解
开发语言·c++·笔记·学习·状态模式
狼哥16865 小时前
蛋糕美食元服务_我的实现指南
ui·harmonyos
祭曦念5 小时前
BLOG_垃圾分类查询应用开发实战
华为·harmonyos
狼哥16865 小时前
蛋糕美食元服务_美食实现指南
ui·harmonyos
sensen_kiss6 小时前
CPT304 SoftwareEngineeringII 软件工程 2 Pt.8 软件测试 (Software Testing)(上)
学习·软件工程