Harmony Development Ts Quick Start

1. Introduction to programming languages

ArkTS is the preferred main application development language for HarmonyOS. Based on TypeScript (TS for short), it matches the ArkUI framework and expands corresponding capabilities such as declarative UI and state management, allowing developers to develop cross-terminal applications in a more concise and natural way. To understand what is ArkTS, we first need to understand the relationship between ArkTS, TypeScript and JavaScript:

  • JavaScript is a high-level scripting language belonging to the network. It has been widely used in the development of web applications. It is often used to add various dynamic functions to web pages to provide users with smoother and more beautiful browsing effects.
  • TypeScript is a superset of JavaScript. It extends the syntax of JavaScript. It is built by adding static type definitions on the basis of JavaScript. It is an open source programming language.
  • ArkTS is compatible with the TypeScript language, and expands capabilities such as declarative UI, state management, and concurrent tasks.

It can be seen that TypeScript is a superset of JavaScript, and ArkTS is a superset of TypeScript. Their relationship is shown in the figure below:
insert image description here
Before learning the related grammar of ArkTS declaration, we first learn the basic grammar of TypeScript.

2. Basic type

TypeScript supports some basic data types, such as booleans, arrays, strings, etc. The following are examples of some of the more commonly used data types, let's understand their basic usage.

  • Boolean value

Boolean can be used in TypeScript to indicate that this variable is a Boolean value and can be assigned a value of true or false.

let isDone: boolean = false;
  • number

All numbers in TypeScript are floating point numbers, and the type of these floating point numbers is number. In addition to supporting decimal, it also supports binary, octal, and hexadecimal.

let decLiteral: number = 2023;
let binaryLiteral: number = 0b11111100111;
let octalLiteral: number = 0o3747;
let hexLiteral: number = 0x7e7;
  • string

TypeScript uses string to represent the text data type, and you can use double quotes ( ") or single quotes (') to represent strings.

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

TypeScript has two ways to define arrays. The first one can be followed by [] after the element type, which means an array composed of elements of this type.

let list: number[] = [1, 2, 3];
The second way is to use array generics, Array<element type>.

let list: Array<number> = [1, 2, 3];
  • tuple

The tuple type allows representing an array with a known number and type of elements, which do not have to be of the same type. For example, you can define a pair of tuples whose values ​​are string and number.

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

The enum type is a supplement to the JavaScript standard data type. Using the enumeration type can give a group of values ​​​​a friendly name.

enum Color {Red, Green, Blue};
let c: Color = Color.Green;
  • Unknown

Sometimes, we will want to assign a type to variables whose type is not clear at the programming stage. In this case, we don't want the type checker to check these values ​​and let them pass the compilation phase check directly. Then we can use the unknown type to mark these variables.

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

When a function does not return a value, you will usually see that its return type is void.

function test(): void {
   console.log('This is function is void');
}
  • Null and Undefined

In TypeScript, both undefined and null have their own types called undefined and null respectively.

let u: undefined = undefined;
let n: null = null;
  • union type

Union types (Union Types) indicate that the value can be one of many types.

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

3. Conditional statement

Conditional statements are used to perform different actions based on different conditions. A TypeScript conditional statement is a block of code that is determined by the execution result (True or False) of one or more statements.

  • if statement

A TypeScript if statement consists of a Boolean expression followed by one or more statements.

var num:number = 5
if (num > 0) { 
   console.log('数字是正数') 
}
  • if...else statement

An if statement can be followed by an optional else statement, which is executed if the Boolean expression is false.

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

if...else The if...else statement is useful when executing multiple judgment conditions.

var num:number = 2 
if(num > 0) { 
    console.log(num+' 是正数') 
} else if(num < 0) { 
    console.log(num+' 是负数') 
} else { 
    console.log(num+' 为0') 
}
  • switch...case statement

A switch statement allows testing when a variable is equal to multiple values. Each value is called a case, and the variable being tested is checked for each switch case.

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

4. Function

A function is a group of statements that together perform a task. The function declaration tells the compiler the function's name, return type, and parameters. TypeScript can create named functions and anonymous functions, which are created as follows:

// 有名函数
function add(x, y) {
  return x + y;
}

// 匿名函数
let myAdd = function (x, y) {
  return x + y;
};
  • define a type for the function

In order to ensure the accuracy of input and output, we can add types to the above function:

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

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

In TypeScript, we can use ? next to the parameter name to realize the function of optional parameters. For example, we want to make lastName optional:

function buildName(firstName: string, lastName?: string) {
    if (lastName)
        return firstName + ' ' + lastName;
    else
        return firstName;
}

let result1 = buildName('Bob');
let result2 = buildName('Bob', 'Adams'); 
  • remaining parameters

The remaining parameters are treated as an unlimited number of optional parameters. There can be none, or any number. It can be defined using an ellipsis ( ...):

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

let employeeName = getEmployeeName('Joseph', 'Samuel', 'Lucas', 'MacKinzie');
  • arrow function

The ES6 version of TypeScript provides an arrow function, which is a shorthand syntax for defining anonymous functions for function expressions, which omits the function keyword. The definition of an arrow function is as follows, and its function is a statement block:

( [param1, parma2,…param n] )=> {
    // 代码块
}

Among them, the input parameters of the function are in the brackets, and there can be 0 to more parameters, and the code block of the function is behind the arrow. We can assign this arrow function to a variable as follows:

let arrowFun = ( [param1, parma2,…param n] )=> {
    // 代码块
}

How to actively call this arrow function, you can call it as follows:

arrowFun(param1, parma2,…param n)

Next, let's see how to convert our familiar function definition method into an arrow function. We can define a function to judge positive and negative numbers, as follows:

function testNumber(num: number) {
  if (num > 0) {
    console.log(num + ' 是正数');
  } else if (num < 0) {
    console.log(num + ' 是负数');
  } else {
    console.log(num + ' 为0');
  }
}

Its calling method is as follows:

testNumber(1)   //输出日志:1 是正数

If this function is defined as an arrow function, the definition looks like this:

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

Its calling method is as follows:

testArrowFun(-1)   //输出日志:-1 是负数

Later, we will often use arrow functions when learning HarmonyOS application development. For example, to add a click event to a button, the function in the onClick event is an arrow function.

Button("Click Now")
  .onClick(() => {
    console.info("Button is click")
})

5. class

TypeScript supports class-based object-oriented programming. The keyword to define a class is class, followed by the class name. A class describes the properties and methods common to the objects created.

  • class definition

For example, we can declare a Person class, which has 3 members: one is an attribute (including name and age), one is a constructor, and one is a getPersonInfo method, which is defined as follows.

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}`;
  }
}

Through the above Person class, we can define a character Jacky and obtain his basic information, which is defined as follows:

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

Inheritance means that the subclass inherits the characteristics and behaviors of the parent class, so that the subclass has the same behavior as the parent class. TypeScript allows the use of inheritance to extend existing classes, and the corresponding keyword is 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}`;
  }
}

Through the above Employee class, we can define a character Tom, here we can get his basic information and his employer information, which is defined as follows:

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

In TypeScript, there are public, private, and protected modifiers. For their functions and specific usage scenarios, you can refer to the relevant learning materials of TypeScript for extended learning.

6. Module

As applications grow larger, it is common to split the code into multiple files, known as modules. Modules can load each other, and can use the special directives export and import to exchange functionality, calling functions of one module from another.

The relationship between two modules is established by using import and export at the file level. Variables, functions, and classes inside a module are not visible outside the module unless they are explicitly exported using export. Similarly, we have to import variables, functions, classes, etc. exported by other modules via import.

  • export

Any declaration (such as variable, function, class, type alias or interface) can be exported by adding the export keyword. For example, if we want to export the NewsData class, the code is as follows:

export class NewsData {
  title: string;
  content: string;
  imagesUrl: Array<NewsFile>;
  source: string;

  constructor(title: string, content: string, imagesUrl: Array<NewsFile>, source: string) {
    this.title = title;
    this.content = content;
    this.imagesUrl = imagesUrl;
    this.source = source;
  }
}
  • import

Importing a module is as easy as exporting it. Exports from other modules can be imported using one of the following import forms.

import { NewsData } from '../common/bean/NewsData';

7. Iterators

An object is considered iterable when it implements the Symbol.iterator property. Some built-in types such as Array, Map, Set, String, Int32Array, Uint32Array, etc. are iterable.

  • for...of statement

for...of will traverse the iterable object and call the Symbol.iterator method on the object. Here's a simple example of using for...of on an array:

let someArray = [1, "string", false];

for (let entry of someArray) {
    console.log(entry); // 1, "string", false
}
  • for…of vs. for…in statements

Both for...of and for...in iterate over a list, but the values ​​used to iterate are different: for...in iterates the keys of the object, while for...of iterates the values ​​of the object.

let list = [4, 5, 6];

for (let i in list) {
    console.log(i); // "0", "1", "2",
}

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

8. Follow-up study

TypeScript is an open source programming language. This chapter only introduces the basic grammar knowledge of TypeScript. For more information, you can refer to the official tutorial of TypeScript (https://www.typescriptlang.org/docs/). During the learning process, if you do not have a TypeScript development environment, you can also directly use the online Playground platform (https://www.typescriptlang.org/play) for coding exercises. Students who have mastered the basics of TypeScript programming can skip the study of this chapter. Students who have not been exposed to TypeScript can first fill in the relevant grammatical foundation, and then enter the development and learning journey of HarmonyOS.

Guess you like

Origin blog.csdn.net/xiaopihair123/article/details/132269719