【Harmony OS 4.0】TypeScript 快速入门

发布于:2024-08-22 ⋅ 阅读:(26) ⋅ 点赞:(0)

1. 常用定义类型

1.1 boolean 类型

let isOff: boolean = true
let isOn: boolean = false

1.2 数字类型

let a: number = 2

1.3 字符串类型

let aStr:string = "hello"

1.4 俩种数组类型

let arr1:number[] = [1, 3, 5]
let arr2: Array<string> = ["hello", "world"]

// HarmonyOS 项目实战
export default class ItemDate {
  img: Resource
  title: Resource
  others?: Resource

  constructor(img: Resource, title: Resource, others?: Resource) {
    this.img = img
    this.title = title
    this.others = others
  }
}
getFirstGridData(): Array<ItemDate> {
  let firstGridData: ItemDate[] = [
    new ItemDate($r('app.media.startIcon'), $r('app.string.my_love')),
    new ItemDate($r('app.media.startIcon'), $r('app.string.history_record'))
  ]
  return firstGridData
}

// 1.4.1 回顾splice用法,改变原数组,返回修改后的数组
let arr3 = [1, 3, 5, 7]
arr3.splice(2, 0, 3) // 把值3添加到下标2的地方
console.log(arr3) // [1, 3, 3, 5, 7]
arr3.splice(4, 1) // 删除下标4的值
console.log(arr3) // [1, 3, 3, 5]

1.5 元组类型 ==> 允许表示一个已知元素数量和类型的数组,各元素的类型不必相同。

let arr4: [string, number]
arr4 = ['hello', 100]
arr4 = [100, 'hello'] // error demo
arr4 = ['hello', 100, 200] // error demo

1.6 枚举类型 enum

  1. 是对 javascript 标准数据类型的一个补充,可以为一组数值赋予友好的名字。
  2. 其主要功能是定义一组有限的选项,例如 方向(上,下,左,右),季节(春,夏,球,冬)等概念都可以使用枚举类型定义
  3. 枚举的定义需使用 enum 关键字
// 1. 基本语法
enum Color { red, green, blue }
let c: Color = Color.green

// 2. 典型使用场景
enum Direction {
  UP,
  BOTTOM,
  LEFT,
  RIGHT
}

function move(direction: Direction) {
  if (direction === Direction.UP) {
    console.log('向上移动')
  } else if (direction === Direction.BOTTOM) {
    console.log('向下移动')
  }else if (direction === Direction.LEFT) {
    console.log('向左移动')
  } else (direction === Direction.RIGHT) {
    console.log('向右移动')
  }
}
move(Direction.UP)

1.6.1 枚举类型赋值

  1. 枚举实际上是一个对象,每个枚举值都是该对象的属性,并且每个属性都有具体的值,属性值只支持俩种类型——数字、字符串。
  2. 默认情况下,每个属性的值都是数字,并且从0开始递增。
  3. 可以手动为每个属性赋值
enum FontSize {
  Small = 12,
  Medium = 16,
  Large = 20,
  ExtraLarge = 24
}

1.7 任意类型 any/Unknown ==> 不清楚类型的变量,不希望类型检查器对这些值进行检查,直接通过编译阶段的检查。

let noSure: any/unknown
noSure = 4
noSure = true

1.8 函数返回值类型 viod ==> 函数没有返回值,可以用 : void 作为函数返回值类型,其含义为空

function myfunc(): void {
	// 这里不能有return
}

1.9 Null ==> 空值,没有给它分配内存,内存中没有变量;

1.10 undefined ==> 未定义的变量,有这个变量,但是没有定义

1.11 联合类型

let a: string | number
a = 'hello'
a = 100

1.12 对象类型

// 1. 对象类型的变量可以通过对象字面量{name: '仙女', age: 18}进行初始化
let person: {name: string, age: number} = {name: '仙女', age: 18}

// 2. 声明一个接口来描述该对象的类型
interface Person {
	name: string, 
	age: number
}
let person: Person = {name: '仙女', age: 18}

2. 条件语句

// 1. if
// 2. if...else 
// 3. if...else if...else ...else
// 4. switch...case,用来做多条件的等于判断
let gender: string = 'mail'
switch (gender) {
	case 'mail': {
		console.log('男')
		break; // 满足条件就终止判断
	}
	case 'femail': {
		console.log('女')
		break;
	}
	default: { // 上面所有case条件都不满足,就会进入default
		console.log('不能确定性别')
		break;
	}
}

3. 循环语句

// 1. 
let i: numebr;
for(i = 1;i <= 10;i++) {
	console.log(i)
}

// 2. 只能针对集合或者是列表
let j: any
// let j: unkonwn
let nums: Array<number> = [12, 23, 56, 32]
for (j in nums) {
	console.log(nums[j])
}

4. 函数

4.1 有名函数

function add(x: number, y: number): void{}
add(10, 20)

4.2 匿名函数

let add_Func = function(x: number, y: number): number{
	return x + y
}
add_Func(10, 20)

let arr: number[] = [2,4,3,5]
arr.forEach(function(item: number) {
	console.log(item)
})

4.3 箭头函数 ==> 匿名函数的简写语法

let fn = (x: number, y: number) => {}

let arr: number[] = [2,4,3,5]
arr.forEach(item: number => console.log(item)

4.4 可选参数函数

  1. 调用可选参数函数时,未传递可选参数,则该参数的值为undefined
function fn(x: number, name?: string) :void {
	if (name == undefined) {
		name = '未定义的变量'
	}
}
fn(10)

4.5 默认参数函数

function fn(x: number, name: string = '未定义的变量') :void {}
fn(10)

4.6 剩余参数函数 ==> 个数不限的可选参数函数

function fn(x: number, ...other: Array<any>) :void {}
fn(10, 'hello', 30)

5. 类(class)

5.1 访问修饰符

  1. 用于控制类成员(属性、方法等)的可访问性。
  2. public 公有的,可以在任何地方被访问到,默认所有的属性和方法都是 public 的
  3. private 私有的,只能在声明它的类中被访问,包括继承的子类也是无法访问到,因此别人在类外面不能随意改动。
    在 ArkTs 中,private 必须本地初始化。
  4. protected 是受保护的,只能在声明它的类和其子类中被访问。
    从创建的对象访问属性和方法是访问不到的。
  5. 通过访问修饰符能够限制一些非法的不安全的访问操作。例如声明银行账户余额必须用private

5.2 定义类、创建对象

// 定义一个Person类
class Person {
	// 实例属性
	private name: string
	private age: number
	// 构造器,定义构造函数,不需要声明返回值类型
	constructor(name: string, age: number){
		this.name = name
		this.age = age
	}
	// 实例方法
	public getPersonInfo(): string { // 公共成员函数
		return 	`我的名字是${this.name},年龄是${this.age}`
	}
}
// 创建对象
let p: Person = new Person('张三'18)
// 访问对象方法
p.getPersonInfo()

5.3 静态成员

  1. 静态成员(静态属性和静态方法)隶属于类本身,而不属于某个对象实例。
  2. 通常用于定义一些常量或者工具方法。
  3. 定义静态成员需要使用 static 关键字
class Constants {
	static count: number = 1
}
Constants.count

class Utils {
	static toLowerCase(str: string) {
		return str.toLowerCase()
	}
}
Utils.toLowerCase('hello word')

5.4 继承

  1. 子类可以直接使用父类的特性,并添加新特性、覆盖现有的特性
  2. 类的继承关键字 extends
  3. 子类构造器使用 super() 继承自父类属性进行初始化
  4. 子类使用 this 关键字访问继承自父类的属性和方法
  5. 子类使用 super 关键字可以访问父类当中所定义的同名方法
class Person {
	private name: string
	private age: number
	
	constructor(name: string, age: number){
		this.name = name
		this.age = age
	}
	
	public getPersonInfo(): string {
		return 	`我的名字是${this.name},年龄是${this.age}`
	}
}
// 定义一个Employee类继承Person
class Employee extends Person {
	private department: string;
	
	constructor(name: string, age: number, department: string){
		// 调用父类的构造函数初始化
		super(name, age)
		this.department = department
	}
	
	public getEmployeeInfo() :string {
		return this.getPersonInfo() + `,我的工作部门是${this.department}`
	} 
	// 如果父子类方法名相同时,可以使用 super 关键字继承父类定义的方法
	public getPersonInfo() :string {
		return super.getPersonInfo() + `,我的工作部门是${this.department}`
	}
}
let emp = new Employee('王五', 26, '行政部')
emp.getEmployeeInfo()
emp.getPersonInfo()

6. 接口

  1. 接口通常会作为一种契约或规范让类(class)去遵守,确保类实现某些特定的行为或功能。

6.1 定义接口

  1. 使用 interface 关键字,通常情况下接口中只包含属性和方法的声明,而不包含具体的实现细节,具体的细节由其 实现类 完成。
interface Person {
	id: number
	name: string
	age: number

	introduce(): void
}

创建实现类,实现接口

  1. 接口的实现需要用到 implements 关键字,实现类 中,需要包含接口属性的赋值逻辑,以及接口方法的实现逻辑。
// Person接口的 实现类Student
class Student implements Person {
	id: number
	name: string
	age: number
	
	constructor(id: number, name: string, age: number) {
		this.id = id
		this.name = name
		this.age = age
	}
	
	introduce(): void{
		console.log('Hello,I am a student')
	}
}
let p1: Person = new Student(1, '小美', 18)

6.2 多态

  1. 多态是面向对象编程中的一个重要概念,它可以使同一类型的对象具有不同的行为。
class Teacher implements Person {
	id: number
	name: string
	age: number
	
	constructor(id: number, name: string, age: number) {
		this.id = id
		this.name = name
		this.age = age
	}
	
	introduce(): void{
		console.log('Hello,I am a teacher')
	}
}
let p2: Person = new Teacher(2, '大帅', 38)
// 同样是 Person 类型的俩个对象,调用同一个 introduce() 方法时,表现出了不同的行为,这就是多态。
p1.introduce()
p2.introduce()

6.3 订单支付系统案例

class Order {
  totalAmount: number
  paymentStrategy: PaymentStrategy

  constructor(totalAmount: number, paymentStrategy: PaymentStrategy) {
    this.totalAmount = totalAmount
    this.paymentStrategy = paymentStrategy
  }

  pay(): void {
    this.paymentStrategy.pay(this.totalAmount)
  }
}

interface PaymentStrategy {
  pay(amount: number): void
}

class AliPay implements PaymentStrategy {
  pay(amount: number): void {
    console.log(`AliPay: ${amount}`)
  }
}

class WeChatPay implements PaymentStrategy {
  pay(amount: number): void {
    console.log(`WeChatPay: ${amount}`)
  }
}

let o1 = new Order(100, new AliPay())
o1.pay()
let o2 = new Order(200, new WeChatPay())
o2.pay()

7. 可迭代对象

  1. 当一个对象实现了 Symbol.iterator 属性时,它是可迭代的。(可以通过for…of循环遍历的对象)。
    一些内置的类型如 Array, Map, Set, String, Int32Array, Uint32Array 等都具有可迭代性。
  2. 迭代器都是可迭代对象
    可迭代对象是迭代器的一个子集
// 1. for..of 语句,针对可迭代对象才能使用,i 代表其中元素,不指下标。
let str: string = 'sdfs'
for(let i of str) {
	console.log(i) // s d f s
}

// 2. map类型,每个元素都是由俩个组成:key,value
let map1 = new Map<string, number>()
map1.set('a', 111)
map1.set('b', 222)
map1.set('c', 333)
for(let j of map1) {
	console.log(j) // ['a', 111] ['b', 222] ['c', 333]
	console.log(j[1]) // 111 222 333
}

8. 模块

前端模块化,在 ArkTs中,常用 ES6 模块化。