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

发布于:2024-07-01 ⋅ 阅读:(56) ⋅ 点赞:(0)

官方文档:ArkTS语言介绍


[代码总结]

声明变量

let hi: string = 'hello';
let hi2 = 'hello, world';    // 自动类型推断

声明常量

const hello: string = 'hello';

数据类型 缺:byte char

Number类型 short int long float double

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

let isDone: boolean = false;

String类型

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

Void类型

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

Object类型

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

Array类型

let names: string[] = ['Alice', 'Bob', 'Carol'];

Enum类型

enum ColorSet { Red, Green, Blue }
let c: ColorSet = ColorSet.Red;

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

Union类型

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类型为匿名类型(数组、函数、对象字面量或联合类型)提供名称,或为已有类型提供替代名称

type Matrix = number[][];
type Handler = (s: string, no: number) => string;
type Predicate <T> = (x: T) => Boolean;
type NullableObject = Object | null;

网站公告

今日签到

点亮在社区的每一天
去签到