HarmonyOS第二课,TypeScript语法知识

发布时间 2023-12-12 11:24:42作者: Hei蛋炒饭

1、TypeScript中常用的变量类型

1、布尔值

TypeScript 中可以使用 boolean 来表示这个变量是布尔值,可以赋值为 true 或者 false 。

 let isDone : boolean = false ;

2、数字

TypeScript 里的所有数字都是浮点数,这些浮点数的类型是 number 。除了支持十进制,还支持二进制、八进制、十六进制。

 let decLiteral : number =2023;		console . log (' decLiteral is '+ decLiteral );
 let binaryLiteral : number =0b11111100111;		console . log (' binaryLiteral is '+ binaryLiteral );
 let octalLiteral : number =0o3747;		 console . log (" octalLiteral is '+ octalLiteral );
 let hexLiteral : number =0x7e7;		 console . log (' hexLiteral is '+ hexLiteral );

3、字符串

TypeScript 里使用 string 表示文本数据类型,可以使用双引号(")或单引号(')表示字符串。

 let name : string =" Jacky ";
 name =" Tom ";
 name =' Mick ';

4、数组

TypeScript 支持以下两种方式声明数组:第一种,可以在元素类型后面接上[],表示由此类型元素组成的一个数组;第二种方式是使用数组泛型, Array <元素类型>。

 let list1: number []=[1,2,3];
 let list2: Array < number >=[1,2,3];

5、元组

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

let x :[ string , number ];
 x =[ hello ',10];// OK 
 x =[10,' hello '];// Error 

6、枚举

enum 类型是对 JavaScript 标准数据类型的一个补充,使用枚举类型可以为一组数值赋予友好的名字。

 enum Color ( Red , Green , Blue );
 let c : Color = Color . Green ;

7、 unknown

有时候,我们会想要为那些在编程阶段还不清楚类型的变量指定一个类型。那么我们可以使用 unknown 类型来标记这些变量。

 let notSure : unknown =4;
 notSure =' maybe a string instead ;
 notSure = false ;

8、 void

当一个函数没有返回值时,你通常会见到其返回值类型是 void 。

function test (): void {
 console . log ( This is function is void ");
}

9、 null 和 undefined

TypeScript 里, undefined 和 null 两者各自有自己的类型分别叫做 undefined 和 null 。

 let u : undefined = undefined ;
 let n : null = null ;

10、联合类型【最常用】

联合类型( Union Types )表示取值可以为多种类型中的一种。

 let myFavoriteNumber : string | number ;
 myFavoriteNumber =' seven ';
 myFavoriteNumber =7;

2条件语句定义

if语句

let num:number = 5
if(num > 0){
console.log('数字是正数');
}

if...else语句

let num:number = 12;
if(num % 2 == 0){
console.log('偶数');
}else{
console.log('奇数');
}

if...else if...else语句

let num:number = 0
if(num > 0){
console.log('是正数');
}else if(number < 0){
console.log('是负数');
}else{
console.log('是0');
}

switch case

var grade:string = 'A';
switch(grade){
case 'A':{
console.log('优');
break;
}
case 'A':{
console.log('优');
break;
}
case 'B':{
console.log('良');
break;
}
case 'C':{
console.log('及格');
break;
}
case 'D':{
console.log('不及格');
break;
}
default {
console.log('非法输入');
break;
}
}

3函数的定义

函数是一组一起执行一个任务的语句,函数声明要告诉编译器函数的名称、返回类型和参数。TypeScript可以创建有名字的函数和匿名函数

//有名字的函数: 给变量设置为number类型
function add (x:number, y:number): number {
  return x + y;
}

//匿名函数:给变量设置为number类型
let myAdd = function(x:number, y:number): number {
 return x + y;
}

//在TypeScript中可以在参数名旁边使用(?)实现可选参数的功能。
function buildName(firstName:string, lastName?:string){
  if(lastName){
      return firstName + ' ' + lastName;
  }else{
      return firstName;
  }
}

//剩余参数会被当作个数不限的可选参数。可以一个没有,同样也可以有任意个
//可以使用省略号(...)进行定义;

function getEmployeeName(firstName:string, ...restOfName:string[]){
  return firstName + ' ' + restOfName.join(' ');
}

let employeeName1 = getEmployeeName('TOM');
let employeeName2 = getEmployeeName('TOM', 'Sandy', 'Lucas', 'Mick');

//箭头函数
([param1, param2, ...paramn]) => {
 //代码块
}

//箭头函数可以赋值给一个变量
let arrowFun = ([param1, param2, ...paramn]) => {
  //代码块
}

//常用函数定义转为箭头函数
function add (x:number, y:number): number {
  return x + y;
}

let arrowFun = (x:number, y:number): number => {
	return x + y;
} 

4 类的定义

TypeScript支持基于类的面向对象的编程方式,定义类的关键字为class,后面紧跟类名。类描述了所创建的对象共同的属性和方法

class Person{
	private name: string
	private age: number
	
	constructor(name:string, age: number){
		this.name = name;
		this.age = age;
	}
	
	public getPersonInfo():string{
		return `My name is ${this.name} and age is ${this.age}`
	}
}

let person1 = new Person('Jacky', 18);
person1.getPersonInfo();

5 类的继承

继承就是子类继承父类的特征和行为,使得子类具有父类相同的行为。TypeScript中允许使用继承来扩展现有的类,对应的关键字为extends

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() + ` and work in $(this.department)`;
	}
}

let person2 = new Employee('Tom', 28, 'HuaWei');
person2.getPersonInfo();
person2.getEmployeeInfo();

6 模块

随着应用越来越大,通常要将代码拆分成多个文件,即所谓的模块(module)。模块可以相互加载,并可以使用特殊的指令 export 和 import 来交换功能,从另一个模块调用一个模块的函数。两个模块之间的关系是通过在文件级别上使用import和export建立的。模块里面的变量、函数和类等在模块外部是不可见的,除非明确地使用export导出它们。类似地,我们必须通过import导入其他模块导出的变量、函数、类等。

export class NewsData{
	title:string;
	content:string;
	
	constructor(title: string, content: string){
		this.title = title;
		this.content = content;
	}
}

//其他文件中导入类
import {NewsData} from '../common/bean/NewsData';

7 迭代器

当一个对象实现了Symbol.iterator属性时,我们认为它是可迭代的。一些内置的类型如Array,Map,Set,String,Int32Array,Uint32Array等都具有可迭代性。

//for...of语句
let someArray = [1, "string", false];

for (let entry of someArray){
	console.log(entry);
}


//for...of vs for...in 语句
let list = [4,5,6]

//for...in对下标进行遍历
for (let i in list){
	console.log(i); // "0", "1", "2"
}


for (let i of list){
	console.log(i); // "4", "5", "6"
}