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

官方文档: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;
相关推荐
敏叔V58724 分钟前
AI智能体的工具学习进阶:零样本API理解与调用
人工智能·学习
2501_941864961 小时前
科学方法论破解学习时间堆砌误区
学习
傻小胖2 小时前
22.ETH-智能合约-北大肖臻老师客堂笔记
笔记·区块链·智能合约
1024小神2 小时前
SVG标签中path路径参数学习
学习
浅念-2 小时前
C++入门(2)
开发语言·c++·经验分享·笔记·学习
ZH15455891312 小时前
Flutter for OpenHarmony Python学习助手实战:面向对象编程实战的实现
python·学习·flutter
简佐义的博客2 小时前
生信入门进阶指南:学习顶级实验室多组学整合方案,构建肾脏细胞空间分子图谱
人工智能·学习
近津薪荼2 小时前
dfs专题4——二叉树的深搜(验证二叉搜索树)
c++·学习·算法·深度优先
rannn_1113 小时前
【苍穹外卖|Day4】套餐页面开发(新增套餐、分页查询、删除套餐、修改套餐、起售停售)
java·spring boot·后端·学习
王码码20353 小时前
Flutter for OpenHarmony 实战之基础组件:第三十一篇 Chip 系列组件 — 灵活的标签化交互
android·flutter·交互·harmonyos