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

官方文档: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一张“业务概念地图“:本体如何从哲学走向企业智能
大数据·人工智能·经验分享·笔记·学习·学习方法·政务
XiHongShi20161 天前
STM32F407 RTC定时器例程,建议保存
stm32·单片机·学习
爱吃苹果的日记本1 天前
离散数学第六课
学习·离散数学
youyin1 天前
HarmonyOS ArkUI 组件与自定义组件零基础:从搭页面到组件化开发
华为·harmonyos
AI职业加油站1 天前
AI智能体应用工程师证书:政策红利下的职业新风口
大数据·运维·人工智能·学习·职场发展
深圳老胡1 天前
STM32F407 控制 L6470 步进电机驱动 —— 控制过程简介
笔记·stm32·单片机·嵌入式硬件·代码规范
旖旎夜光1 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
奇思妙想聪明勤奋的小羊1 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
Because_of_Her11 天前
并查集-听课笔记
笔记·算法·并查集