一、声明
变量声明
以关键字 let 开头的声明引入变量,该变量在程序执行期间可以具有不同的值。
let hi: string = 'hello';
hi = 'hello, world';
常量声明
以关键字 const 开头的声明引入只读常量,该常量只能被赋值一次。
const hello: string = 'hello';
二、类型
Number类型
number 类型覆盖了任何整数和浮点数。
let integer: number = 12;
const floast: number = 0.2;
const hexNum: number = 0xF7F7F7;
Boolen类型
boolean 类型由 true 和 false 两个逻辑值组成。
let success: boolean = true;
if (success) {
// do something
}
String类型
string代表字符序列,可以使用转义字符来表示字符。
const str1 = "title";
const str2 = 'detail';
const str3 = str1 + ' ' + str2;
const content = `content: ${str3}`;
console.log(content);
const value = ''
if (value) {
// value为空字符,不会触发if条件
}
Array类型
array类型是由可赋值给数组声明中指定的元素类型的数据组成的对象。
const arr1 = new Array<string>();
arr1.push('a');
arr1.pop();
const arr2: string[] = [];
arr2.push('b');
console.log(`length: ${arr2.length}`);
Object类型
object类型是所有引用类型的基类型。
1)定义对象属性,创建对象并赋值
interface Customer {
name: string,
age: number,
job?: string,
interest: string | undefined
}
class Demo {
demo(): void {
const peter: Customer = {
name: 'Peter',
age: 27,
interest: undefined
};
peter.job = 'engineer';
this.test(peter);
}
test(arg: object): void {
// do something
}
}
2)直接创建对象并赋值
class Demo {
demo(): void {
const peter: object = new Object();
peter['name'] = 'Peter'
peter['age'] = 15
peter['job'] = 'student'
peter['interest'] = undefined
this.test(peter);
}
test(arg: object): void {
// do something
}
}
Void类型
void类型用于指定函数没有返回值。
function getDeviceId(): void {
// do somethind
}
Enum类型
enum枚举类型用于声明一组命名的常数。
// 声明
enum Direction {
LEFT,
RIGHT,
TOP,
BOTTOM
}
// 应用
const direction = Direction.LEFT
三、语句
if语句
if (condition) {
// do something
}
switch语句
switch (type) {
case 0:
// do something
break;
case 1:
case 2: // 同时命中1和2
// do something
break;
default:
}
for语句
const arr: string[] = ['a', 'b', 'c', 'd', 'e']
for (let i=0; i<arr.length; i+=1) {
const str = arr[i]
if (str === 'd') {
break
}
// do something
}
const arr: string[] = ['a', 'b', 'c', 'd', 'e']
for (let str of arr) {
if (str === 'b') {
continue
}
// do something
}
const arr: string[] = ['a', 'b', 'c', 'd', 'e']
arr.forEach(str => {
// do something
})
while语句
while (condition) {
// do something
}
do {
// do something
} while (condition)
try-catch语句
try {
// do something
} catch (e) {
console.log(`error: ${e}`)
}
四、运算符
三元运算符
const str = value ? value : ''
const str1 = value ?? ''
加/减运算符
let i = 0
i += 1 // 等价与 i = i+1
let j = 10
j -= 1 // 等价与 j = j-1
可选链运算符
1)变量/属性的定义
let value1: string = 'abc'
value1.length
// value2和value3的命名方式相同
let value2?: string
value2?.length
let value3: string | undefined | null
value3?.length
2)方法可选参数的定义
// 可选参数必须放在必选参数之后
function execute(str1: string, str2?: string): string {
return str1 + (str2 ?? '')
}
execute('a', 'b')
execute('a')
五、函数
函数调用
调用函数以执行其函数体。
function printParams(a: string, b: string, c?: string) {
console.log(`a: ${a}, b: ${b}, c: ${c}`);
}
printParams('a', 'b');
printParams('a', 'b', 'c');
函数类型
函数类型通常用于定义回调。
type callBackFunc = (message: string) => number // 函数类型
function execute(callBack: callBackFunc) {
const code = callBack('success');
console.log(`code: ${code}`);
}
let callBack = (message: string) => {
console.log(`message: ${message}`);
retrun 0;
}
execute(callBack);
六、类
类声明
引入一个新类型,并定义其字段、方法和构造函数。
class Car {
name: string = ''
style: string = ''
price?: number
private identify?: string
constructor() {
this.execute();
}
execute() {
const detail = `${this.name} ${this.style}`;
console.log(detail);
}
}
构造函数
1)不带参数
constructor() {
// do something
}
2)带参数
constructor(name: string, style: string) {
this.name = name;
this.style = style;
// do something
}
3)调用时机
// 不带参数
let car1 = new Car() ;
car1.name = 'Tesla';
car1.style = 'Model 3';
// 带参数
let car1 = new Car('Tesla', 'Model 3');
Get/Set方法
class Car {
name: string = ''
price?: number
setName(name: string) {
this.name = name;
}
getName(): string {
return this.name;
}
setPrice(price?: number) {
this.price = price;
}
getPrice(): number | undefined {
return this.price;
}
}
类继承
class BydCar extends Car {
Batterylife?: number
constructor() {
this.name = 'Byd';
}
execute() {
super.execute();
// do something
}
}
接口定义
interface CarInterface {
drive(): void
}
接口继承
interface BydInterface extends CarInterface {
automaticParking(): void
}
接口实现
class BydCar extends Car implements BydInterface {
constructor() {
this.name = 'Byd';
}
drive(): void {
// drive
}
automaticParking(): void {
// automatic parking
}
}
静态属性
// 声明
class EventConstants {
static readonly AVAILABLE = true
static readonly LOADD_EVENT = 'onLoad'
static readonly UNLOAD_EVENT = 'onUnload'
}
// 应用
const available = EventConstants.AVAILABLE
静态方法
// 声明
class DeviceUtils {
static getDeviceName(): string {
return 'Hua Wei Mate60'
}
}
// 应用
const deviceName = DeviceUtils.getDeviceName()
本文参考于鸿蒙开发者联盟:ArkTS语言介绍