@@ -7,16 +7,16 @@ ArkTS is the preferred main programming language for application development in
...
@@ -7,16 +7,16 @@ ArkTS is the preferred main programming language for application development in
The following syntaxes in TS are restricted in ArkTS:
The following syntaxes in TS are restricted in ArkTS:
- Static typing is enforced. Static typing is one of the most important features of ArkTS. If the program is statically typed, i.e. all types are known at the compile time, it’s much easier to understand which data structures are used in the code. At the same time, since all types are known before the program actually runs, code correctness can be verified by the compiler, which eliminates many runtime type checks and improves the performance.
- Static typing is enforced. Static typing is one of the most important features of ArkTS. If the program is statically typed, that is, all types are known at the compile time, it's much easier to understand which data structures are used in the code. At the same time, since all types are known before the program actually runs, code correctness can be verified by the compiler, which eliminates many runtime type checks and improves the performance.
- Changing object layout in runtime is prohibited. To achieve maximum performance benefits, ArkTS requires that layout of objects does not change during program execution.
- Changing object layout in runtime is prohibited. To achieve maximum performance benefits, ArkTS requires that layout of objects does not change during program execution.
- Semantics of operators is restricted. To achieve better performance and encourage developers to write cleaner code, ArkTS restricts the semantics of operators. Such as, the binary `+` operator supports only for strings and numbers but not for objects.
- Semantics of operators is restricted. To achieve better performance and encourage developers to write cleaner code, ArkTS restricts the semantics of operators. For example, the binary `+` operator is supported for strings and numbers, but not for objects.
-structural typing is not supported. Support for structural typing is a major feature which needs lots of consideration and careful implementation in language specification, compiler and runtime. Currently, ArkTS does not supports structural typing. The team will be ready to reconsider based on real-world scenarios and feedback.
-Structural typing is not supported. Support for structural typing is a major feature that needs lots of consideration and careful implementation in language specification, compiler and runtime. Currently, ArkTS does not supports structural typing. The team will be ready to reconsider this feature based on real-world scenarios and feedback.
The added features offered by ArkTS for ArkUI framework include the following:
The added features offered by ArkTS for the ArkUI framework include the following:
-[Basic syntax](arkts-basic-syntax-overview.md): ArkTS defines declarative UI description, custom components, and dynamic extension of UI elements. All these, together with built-in components, event methods, and attribute methods in ArkUI, jointly underpin UI development.
-[Basic syntax](arkts-basic-syntax-overview.md): ArkTS defines declarative UI description, custom components, and dynamic extension of UI elements. All these, together with built-in components, event methods, and attribute methods in ArkUI, jointly underpin UI development.
Welcome to the tutorial for ArkTS, a TypeScript-based programming language
Welcome to the tutorial for ArkTS, a TypeScript-based programming language designed specifically to build high-performance mobile applications!
designed specifically to build high-performance mobile applications!
ArkTS is optimized to provide better performance and efficiency, while still
ArkTS is optimized to provide better performance and efficiency, while still maintaining the familiar syntax of TypeScript.
maintaining the familiar syntax of TypeScript.
As mobile devices continue to become more prevalent in our daily lives,
As mobile devices continue to become more prevalent in our daily lives, there is a growing need for programming languages optimized for the mobile environment. Many current programming languages were not designed with mobile devices in mind, resulting in slow and inefficient applications that drain battery life. ArkTS has been specifically designed to address such concerns by prioritizing higher execution efficiency.
there is a growing need for programming languages optimized for the
mobile environment. Many current programming languages were not designed with
mobile devices in mind, resulting in slow and inefficient applications that
drain battery life. ArkTS has been specifically designed to address such concerns
by prioritizing higher execution efficiency.
ArkTS is based on the popular programming language TypeScript that extends
ArkTS is based on the popular programming language TypeScript that extends JavaScript by adding type definitions. TypeScript is well-loved by many developers as it provides a more structured approach to coding in JavaScript. ArkTS aims to keep the look and feel of TypeScript to enable a seamless transition for the existing TypeScript developers, and to let mobile developers learn ArkTS quickly.
JavaScript by adding type definitions. TypeScript is well-loved by many developers as it
provides a more structured approach to coding in JavaScript. ArkTS aims to
keep the look and feel of TypeScript to enable a seamless transition for the existing
TypeScript developers, and to let mobile developers learn ArkTS quickly.
One of the key features of ArkTS is its focus on low runtime overhead.
One of the key features of ArkTS is its focus on low runtime overhead.
ArkTS imposes stricter limitations on the TypeScript’s dynamically typed features,
ArkTS imposes stricter limitations on the TypeScript's dynamically typed features, reducing runtime overhead and allowing faster execution. By eliminating the dynamically typed features from the language, ArkTS code can be compiled ahead-of-time more efficiently, resulting in faster application startup and lower power consumption.
reducing runtime overhead and allowing faster execution. By eliminating
the dynamically typed features from the language, ArkTS code can be compiled
Interoperability with JavaScript was a critical consideration in the ArkTS language design. Many mobile app developers already have TypeScript and JavaScript code and libraries they would want to reuse. ArkTS has been designed for seamless JavaScript interoperability, making it easy for the developers to integrate the JavaScript code into their applications and vice versa. This will allow the developers to use their existing codebases and libraries to leverage the power of our new language.
ahead-of-time more efficiently, resulting in faster application startup and
lower power consumption.
To ensure best experience for UI app development for OpenHarmony ecosystem, ArkTS provides support for ArkUI, including its declarative syntax and other features. Since this feature is outside the scope of the "stock" TypeScript, a verbose ArkUI example is provided in a separate chapter.
Interoperability with JavaScript was a critical consideration in the ArkTS language
This tutorial will guide you through the core features, syntax, and best practices of ArkTS. After reading this tutorial through the end, you will be able to build performant and efficient mobile applications in ArkTS.
design. Many mobile app developers already have TypeScript and JavaScript code and libraries
they would want to reuse. ArkTS has been designed for seamless JavaScript
interoperability, making it easy for the developers to integrate the JavaScript code
into their applications and vice versa. This will allow the developers to
use their existing codebases and libraries to leverage the power of our
new language.
To ensure best experience for UI app development for OpenHarmony ecosystem,
ArkTS provides support for ArkUI, including its declarative syntax and other
features. Since this feature is outside the scope of the “stock” TypeScript, a verbose
ArkUI example is provided in a separate chapter.
This tutorial will guide the developers through the core features, syntax,
and best practices of ArkTS. After reading this tutorial through the end,
the developers will be able to build performant and efficient mobile
applications in ArkTS.
# The Basics
# The Basics
...
@@ -50,15 +23,14 @@ applications in ArkTS.
...
@@ -50,15 +23,14 @@ applications in ArkTS.
Declarations in ArkTS introduce:
Declarations in ArkTS introduce:
-variables,
-Variables
-constants,
-Constants
-functions, and
-Functions
-types.
-Types
### Variable Declaration
### Variable Declaration
A declaration starting with the keyword `let` introduces a variable which
A declaration starting with the keyword `let` introduces a variable which can have different values during program execution.
can have different values during program execution.
```typescript
```typescript
lethi:string="hello"
lethi:string="hello"
...
@@ -67,8 +39,7 @@ hi = "hello, world"
...
@@ -67,8 +39,7 @@ hi = "hello, world"
### Constant Declaration
### Constant Declaration
A declaration starting with the keyword `const` introduces a read-only
A declaration starting with the keyword `const` introduces a read-only constant that can be assigned only once.
constant that can be assigned only once.
```typescript
```typescript
consthello:string="hello"
consthello:string="hello"
...
@@ -78,16 +49,13 @@ A compile-time error occurs if a new value is assigned to a constant.
...
@@ -78,16 +49,13 @@ A compile-time error occurs if a new value is assigned to a constant.
### Automatic Type Inference
### Automatic Type Inference
As ArkTS is a statically typed language, the types of all entities, like
As ArkTS is a statically typed language, the types of all entities, like variables and constants, have to be known at compile time.
variables and constants, have to be known at compile time.
However, developers do not need to explicitly specify the type of a declared
However, developers do not need to explicitly specify the type of a declared entity if a variable or a constant declaration contains an initial value.
entity if a variable or a constant declaration contains an initial value.
All cases that allow the type to be inferred automatically are specified in
the ArkTS Specification.
Both variable declarations are valid, and both variables are of the `string`
All cases that allow the type to be inferred automatically are specified in the ArkTS Specification.
type:
Both variable declarations are valid, and both variables are of the `string` type:
```typescript
```typescript
lethi1:string="hello"
lethi1:string="hello"
...
@@ -96,32 +64,30 @@ let hi2 = "hello, world"
...
@@ -96,32 +64,30 @@ let hi2 = "hello, world"
## Types
## Types
`Class`, `interface`, `function`, `enum`, `union` types, and type
`Class`, `interface`, `function`, `enum`, `union` types, and type `aliases` are described in the corresponding sections.
`aliases` are described in the corresponding sections.
### Numeric Types
### Numeric Types
ArkTS has `number` and `Number` numeric types. Any integer and
ArkTS has `number` and `Number` numeric types. Any integer and floating-point values can be assigned to a variable of these types.
floating-point values can be assigned to a variable of these types.
Numeric literals include integer literals and floating-point literals
Numeric literals include integer literals and floating-point literals
with the decimal base.
with the decimal base.
Integer literals include the following:
Integer literals include the following:
*decimal integers that consist of a sequence of digits. For example: `0`, `117`, `-345`;
*Decimal integers that consist of a sequence of digits. For example: `0`, `117`, `-345`.
*hexadecimal integers that start with 0x (or 0X), and can contain digits (0-9) and letters a-f or A-F. For example: `0x1123`, `0x00111`, `-0xF1A7`;
*Hexadecimal integers that start with 0x (or 0X), and can contain digits (0-9) and letters a-f or A-F. For example: `0x1123`, `0x00111`, `-0xF1A7`.
*octal integers that start with 0o (or 0O) and can only contain digits (0-7). For example: `0o777`;
*Octal integers that start with 0o (or 0O) and can only contain digits (0-7). For example: `0o777`.
*binary integers that start with 0b (or 0B), and can only contain the digits 0 and 1. For example: `0b11`, `0b0011`, `-0b11`.
*Binary integers that start with 0b (or 0B), and can only contain the digits 0 and 1. For example: `0b11`, `0b0011`, `-0b11`.
A floating-point literal includes the following:
A floating-point literal includes the following:
*decimal integer, optionally signed (i.e., prefixed with “+” or “-“);
*Decimal integer, optionally signed (i.e., prefixed with "+" or "-");
*decimal point (“.”);
*Decimal point (".").
*fractional part (represented by a string of decimal digits);
*Fractional part (represented by a string of decimal digits).
*exponent part that starts with “e” or “E”, followed by an optionally signed (i.e., prefixed with “+” or “-”) integer.
*Exponent part that starts with "e" or "E", followed by an optionally signed (i.e., prefixed with "+" or "-") integer.
For example:
Example:
```typescript
```typescript
letn1=3.14
letn1=3.14
...
@@ -139,8 +105,7 @@ function factorial(n: number) : number {
...
@@ -139,8 +105,7 @@ function factorial(n: number) : number {
### `Boolean`
### `Boolean`
The `boolean` type represents logical values that are either `true`
The `boolean` type represents logical values that are either `true` or `false`.
or `false`.
Usually variables of this type are used in conditional statements:
Usually variables of this type are used in conditional statements:
...
@@ -156,12 +121,9 @@ if (isDone) {
...
@@ -156,12 +121,9 @@ if (isDone) {
### `String`
### `String`
A `string` is a sequence of characters; some characters can be set by using
A `string` is a sequence of characters; some characters can be set by using escape sequences.
escape sequences.
A `string` literal consists of zero or more characters enclosed in single
A `string` literal consists of zero or more characters enclosed in single (') or double quotes ("). The special form of string literals are template literals enclosed in backtick quotes (\`).
(’) or double quotes (“). The special form of string literals are template
literals enclosed in backtick quotes (\`).
```typescript
```typescript
lets1="Hello, world!\n"
lets1="Hello, world!\n"
...
@@ -185,18 +147,12 @@ let instance: Class <void>
...
@@ -185,18 +147,12 @@ let instance: Class <void>
### `Object` Type
### `Object` Type
An `Object` class type is a base type for all reference types. Any value,
An `Object` class type is a base type for all reference types. Any value, including values of primitive types (they will be automatically boxed), can be directly assigned to variables of the type `Object`.
including values of primitive types (they will be automatically boxed), can
be directly assigned to variables of the type `Object`.
### `Array` Type
### `Array` Type
An `array` is an object comprised of elements of data types assignable to
An `array` is an object comprised of elements of data types assignable to the element type specified in the array declaration.
the element type specified in the array declaration.
A value of an `array` is set by using *array composite literal*, that is a list of zero or more expressions enclosed in square brackets ([]). Each expression represents an element of the `array`. The length of the `array` is set by the number of expressions. Index of the first array element is 0.
A value of an `array` is set by using *array composite literal*, that is a
list of zero or more expressions enclosed in square brackets ([]). Each
expression represents an element of the `array`. The length of the `array`
is set by the number of expressions. Index of the first array element is 0.
The following example creates the `array` with three elements:
The following example creates the `array` with three elements:
An `enum` type is a value type with a defined set of named values called
An `enum` type is a value type with a defined set of named values called enum constants.
enum constants.
In order to be used, an `enum` constant must be prefixed with an enum `type` name.
In order to be used, an `enum` constant must be prefixed with an enum
`type` name.
```typescript
```typescript
enumColor{Red,Green,Blue}
enumColor{Red,Green,Blue}
letc:Color=Color.Red
letc:Color=Color.Red
```
```
A constant expression can be used to explicitly set the value of an `enum`
A constant expression can be used to explicitly set the value of an `enum` constant.
constant.
```typescript
```typescript
enumColor{White=0xFF,Grey=0x7F,Black=0x00}
enumColor{White=0xFF,Grey=0x7F,Black=0x00}
...
@@ -226,9 +179,7 @@ let c: Color = Color.Black
...
@@ -226,9 +179,7 @@ let c: Color = Color.Black
### `Union` Type
### `Union` Type
A `union` type is a reference type which is created as a combination
A `union` type is a reference type which is created as a combination of other types. Values of union types can be valid values of all types a union was created from.
of other types. Values of union types can be valid values of all types
a union was created from.
```typescript
```typescript
classCat{
classCat{
...
@@ -251,7 +202,7 @@ animal = 42
...
@@ -251,7 +202,7 @@ animal = 42
There are different mechanisms to get a value of a particular type from a union.
There are different mechanisms to get a value of a particular type from a union.
For example
Example:
```typescript
```typescript
classCat{sleep(){};meow(){}}
classCat{sleep(){};meow(){}}
...
@@ -273,8 +224,7 @@ animal.sleep () // Any animal can sleep
...
@@ -273,8 +224,7 @@ animal.sleep () // Any animal can sleep
### Type `Aliases`
### Type `Aliases`
Type `aliases` provide names for anonymous types (array, function, object
Type `aliases` provides names for anonymous types (array, function, object literal or union types) or alternative names for existing types.
literal or union types) or alternative names for existing types.
```typescript
```typescript
typeMatrix=number[][]
typeMatrix=number[][]
...
@@ -287,24 +237,22 @@ type NullableObject = Object | null
...
@@ -287,24 +237,22 @@ type NullableObject = Object | null
### Assignment Operators
### Assignment Operators
Simple assignment operator ‘=’ is used as in “x = y”.
Simple assignment operator '=' is used as in "x = y".
Compound assignment operators combine an assignment with an operator, where
Compound assignment operators combine an assignment with an operator, where `x op = y` equals `x = x op y`.
`x op = y` equals `x = x op y`.
Compound assignment operators are as follows: `+=`, `-=`, `*=`, `/=`,
Compound assignment operators are as follows: `+=`, `-=`, `*=`, `/=`, `%=`, `<<=`, `>>=`, `>>>=`, `&=`, `|=`, `^=`.
| `==` | returns true if both operands are equal |
| `==`| Returns true if both operands are equal. |
| `!=` | returns true if both operands are not equal |
| `!=`| Returns true if both operands are not equal. |
| `>` | returns true if the left operand is greater than the right |
| `>`| Returns true if the left operand is greater than the right. |
| `>=` | returns true if the left operand is greater than or equal to the right |
| `>=`| Returns true if the left operand is greater than or equal to the right. |
| `<` | returns true if the left operand is less then the right |
| `<`| Returns true if the left operand is less than the right. |
| `<=` | returns true if the left operand is less than or equal to the right |
| `<=`| Returns true if the left operand is less than or equal to the right. |
### Arithmetic Operators
### Arithmetic Operators
Unary operators are `-`, `+`, `--` and `++`.
Unary operators are `-`, `+`, `--` and `++`.
...
@@ -333,15 +281,15 @@ Binary operators are as follows:
...
@@ -333,15 +281,15 @@ Binary operators are as follows:
| Operator | Description |
| Operator | Description |
|------------|---------------|
|------------|---------------|
| `a && b` | logical AND |
| `a && b` | Logical AND |
| `a \|\| b` | logical OR |
| `a \|\| b` | Logical OR |
| `! a` | logical NOT |
| `! a` | Logical NOT |
## Control Flow
## Control Flow
### `If` Statements
### `If` Statements
An `if` statement is used to execute a sequence of statements when a logical
An `if` statement is used to execute a sequence of statements when a logical condition is `true`, or another set of statements (if provided) otherwise.
condition is `true`, or another set of statements (if provided) otherwise.
The `else` part can also contain more `if` statements.
The `else` part can also contain more `if` statements.
An `if` statement looks as follows:
An `if` statement looks as follows:
...
@@ -356,9 +304,7 @@ if (condition1) {
...
@@ -356,9 +304,7 @@ if (condition1) {
}
}
```
```
All conditional expressions must be of the type `boolean` or other types
All conditional expressions must be of the type `boolean` or other types (`string`, `number`, etc.). For types other than `boolean`, implicit conversion rules apply:
(`string`, `number`, etc.). For types other than `boolean`, implicit
conversion rules apply:
```typescript
```typescript
lets1="Hello"
lets1="Hello"
...
@@ -374,8 +320,7 @@ if (s2.length != 0) {
...
@@ -374,8 +320,7 @@ if (s2.length != 0) {
### `Switch` Statements
### `Switch` Statements
A `switch` statement is used to execute a sequence of statements that match
A `switch` statement is used to execute a sequence of statements that match the value of a switch expression.
the value of a switch expression.
A `switch` statement looks as follows:
A `switch` statement looks as follows:
...
@@ -397,27 +342,21 @@ default:
...
@@ -397,27 +342,21 @@ default:
}
}
```
```
The `switch` expression type must be of `number`, `enum` or `string`
The `switch` expression type must be of `number`, `enum` or `string` types.
types.
Each label must be either a constant expression or the name of an enum constant.
Each label must be either a constant expression or the name of an enum constant.
If the value of a `switch` expression equals the value of some label, then
If the value of a `switch` expression equals the value of some label, then the corresponding statements are executed.
the corresponding statements are executed.
If there is no match, and the `switch` has the default clause, then the
If there is no match, and the `switch` has the default clause, then the default statements are executed.
default statements are executed.
An optional `break` statement allows to break out of the `switch` and
An optional `break` statement allows you to break out of the `switch` and continue executing the statement that follows the `switch`.
continue executing the statement that follows the `switch`.
If there is no `break`, then the next statements in the `switch` is
If there is no `break`, then the next statements in the `switch` are executed.
executed.
### Conditional Expressions
### Conditional Expressions
The conditional expression `? :` uses the `boolean` value of the first
The conditional expression `? :` uses the `boolean` value of the first expression to decide which of two other expressions to evaluate.
expression to decide which of two other expressions to evaluate.
A conditional expression looks as follows:
A conditional expression looks as follows:
...
@@ -425,9 +364,7 @@ A conditional expression looks as follows:
...
@@ -425,9 +364,7 @@ A conditional expression looks as follows:
condition?expression1:expression2
condition?expression1:expression2
```
```
The condition must be a logical expression. If that logical expression is
The condition must be a logical expression. If that logical expression is `true`, then the first expression is used as the result of the ternary expression; otherwise, the second expression is used.
`true`, then the first expression is used as the result of the ternary
expression; otherwise, the second expression is used.
A `for` statement is executed repeatedly until the specified loop exit
A `for` statement is executed repeatedly until the specified loop exit condition is `false`.
condition is `false`.
A `for` statement looks as follows:
A `for` statement looks as follows:
...
@@ -451,15 +387,10 @@ for ([init]; [condition]; [update]) {
...
@@ -451,15 +387,10 @@ for ([init]; [condition]; [update]) {
When a `for` statement is executed, the following process takes place:
When a `for` statement is executed, the following process takes place:
1. An `init` expression is executed, if any. This expression usually
1. An `init` expression is executed, if any. This expression usually initializes one or more loop counters.
initializes one or more loop counters.
2. The condition is evaluated. If the value of condition is `true`, or if the conditional expression is omitted, then the statements in the `for` body are to be executed. If the value of condition is `false`, then the `for` loop terminates.
2. The condition is evaluated. If the value of condition is `true`, or
if the conditional expression is omitted, then the statements in the
`for` body are to be executed. If the value of condition is `false`,
then the `for` loop terminates.
3. The statements of the `for` body are executed.
3. The statements of the `for` body are executed.
4. If there is an `update` expression, then the `update` expression
4. If there is an `update` expression, then the `update` expression is executed.
is executed.
5. Go back to step 2.
5. Go back to step 2.
Example:
Example:
...
@@ -491,8 +422,7 @@ for (let ch of "a string object") { /* process ch */ }
...
@@ -491,8 +422,7 @@ for (let ch of "a string object") { /* process ch */ }
### `While` Statements
### `While` Statements
A `while` statement has its body statements executed as long as the
A `while` statement has its body statements executed as long as the specified condition evaluates to `true`.
specified condition evaluates to `true`.
A `while` statement looks as follows:
A `while` statement looks as follows:
...
@@ -517,8 +447,7 @@ while (n < 3) {
...
@@ -517,8 +447,7 @@ while (n < 3) {
### `Do-while` Statements
### `Do-while` Statements
`do-while` statements are executed repetitively until a specified
`do-while` statements are executed repetitively until a specified condition evaluates to false.
condition evaluates to false.
A `do-while` statement looks as follows:
A `do-while` statement looks as follows:
...
@@ -555,8 +484,7 @@ while (true) {
...
@@ -555,8 +484,7 @@ while (true) {
}
}
```
```
A `break` statement with a label identifier transfers control out of the
A `break` statement with a label identifier transfers control out of the enclosing statement to the one which has the same label identifier.
enclosing statement to the one which has the same label identifier.
Example:
Example:
...
@@ -573,8 +501,7 @@ label: while (true) {
...
@@ -573,8 +501,7 @@ label: while (true) {
### `Continue` Statements
### `Continue` Statements
A `continue` statement stops the execution of the current loop iteration
A `continue` statement stops the execution of the current loop iteration and passes control to the next iteration.
and passes control to the next iteration.
Example:
Example:
...
@@ -606,8 +533,7 @@ try {
...
@@ -606,8 +533,7 @@ try {
}
}
```
```
The example below shows the `throw` and `try` statements used to handle
The example below shows the `throw` and `try` statements used to handle the zero division case:
the zero division case:
```typescript
```typescript
classZeroDivisorextendsError{}
classZeroDivisorextendsError{}
...
@@ -655,8 +581,7 @@ function processData(s: string) {
...
@@ -655,8 +581,7 @@ function processData(s: string) {
## Function Declarations
## Function Declarations
A function declaration introduces a named function, specifying its name,
A function declaration introduces a named function, specifying its name, parameters, return type and body.
parameters, return type and body.
Below is a simple function with two string parameters and string return type:
Below is a simple function with two string parameters and string return type:
The return type of a function that does not need to return a value can be
The return type of a function that does not need to return a value can be explicitly specified as `void` or omitted altogether. No return statement is needed for such functions.
explicitly specified as `void` or omitted altogether. No return statement
is needed for such functions.
Both notations below are valid:
Both notations below are valid:
...
@@ -740,16 +659,13 @@ function hi2(): void { console.log("hi") }
...
@@ -740,16 +659,13 @@ function hi2(): void { console.log("hi") }
## Function Scope
## Function Scope
Variables and other entities defined in a function are local to the function
Variables and other entities defined in a function are local to the function and cannot be accessed from the outside.
and cannot be accessed from the outside.
If the name of a variable defined in the function is equal to the name of an
If the name of a variable defined in the function is equal to the name of an entity in the outer scope, then the local definition shadows the outer entity.
entity in the outer scope, then the local definition shadows the outer entity.
## Function Calls
## Function Calls
Calling a function actually leads to the execution of its body, while
Calling a function actually leads to the execution of its body, while the arguments of the call are assigned to the function parameters.
the arguments of the call are assigned to the function parameters.
If the function is defined as follows:
If the function is defined as follows:
...
@@ -791,11 +707,9 @@ let sum = (x: number, y: number): number => {
...
@@ -791,11 +707,9 @@ let sum = (x: number, y: number): number => {
}
}
```
```
An arrow function return type can be omitted; in such case, it is inferred
An arrow function return type can be omitted; in such case, it is inferred from the function body.
from the function body.
An expression can be specified as an arrow function to make the notation
An expression can be specified as an arrow function to make the notation shorter, i.e., the following two notations are equivalent:
shorter, i.e., the following two notations are equivalent:
```typescript
```typescript
letsum1=(x:number,y:number)=>{returnx+y}
letsum1=(x:number,y:number)=>{returnx+y}
...
@@ -804,9 +718,7 @@ let sum2 = (x: number, y: number) => x + y
...
@@ -804,9 +718,7 @@ let sum2 = (x: number, y: number) => x + y
## Closure
## Closure
An arrow function is usually defined inside another function. As an inner
An arrow function is usually defined inside another function. As an inner function, it can access all variables and functions defined in the outer functions.
function, it can access all variables and functions defined in the outer
functions.
To capture the context, an inner function forms a closure of its environment.
To capture the context, an inner function forms a closure of its environment.
The closure allows accessing such an inner function outside its own environment.
The closure allows accessing such an inner function outside its own environment.
...
@@ -826,15 +738,12 @@ In the sample above, the arrow function closure captures the `count` variable.
...
@@ -826,15 +738,12 @@ In the sample above, the arrow function closure captures the `count` variable.
## Function Overload Signatures
## Function Overload Signatures
A function can be specified to be called in different ways by writing
A function can be specified to be called in different ways by writing overload signatures. To do so, several functions' headers that have the same name but different signatures are written and immediately followed by the single implementation function.
overload signatures. To do so, several functions’ headers that have the
same name but different signatures are written and immediately followed
@@ -846,11 +755,9 @@ An error occurs if two overload signatures have identical parameter lists.
...
@@ -846,11 +755,9 @@ An error occurs if two overload signatures have identical parameter lists.
# Classes
# Classes
A class declaration introduces a new type and defines its fields, methods
A class declaration introduces a new type and defines its fields, methods and constructors.
and constructors.
In the following example, class `Person` is defined, which has fields
In the following example, class `Person` is defined, which has fields **name** and **surname**, constructor, and a method `fullName`:
‘name’ and ‘surname’, constructor, and a method `fullName`:
```typescript
```typescript
classPerson{
classPerson{
...
@@ -866,8 +773,7 @@ class Person {
...
@@ -866,8 +773,7 @@ class Person {
}
}
```
```
After the class is defined, its instances can be created by using
After the class is defined, its instances can be created by using the keyword `new`:
the keyword `new`:
```typescript
```typescript
letp=newPerson("John","Smith")
letp=newPerson("John","Smith")
...
@@ -887,12 +793,12 @@ let p: Point = {x: 42, y: 42}
...
@@ -887,12 +793,12 @@ let p: Point = {x: 42, y: 42}
## Fields
## Fields
A field is a variable of some type that is declared directly in a class.
A field is a variable of some type that is declared directly in a class.
Classes may have instance fields, static fields or both.
Classes may have instance fields, static fields or both.
### Instance Fields
### Instance Fields
Instance fields exist on every instance of a class. Each instance has its own
Instance fields exist on every instance of a class. Each instance has its own set of instance fields.
set of instance fields.
```typescript
```typescript
classPerson{
classPerson{
...
@@ -917,9 +823,7 @@ this.name
...
@@ -917,9 +823,7 @@ this.name
### Static Fields
### Static Fields
The keyword `static` is used to declare a field as static. Static fields
The keyword `static` is used to declare a field as static. Static fields belong to the class itself, and all instances of the class share one static field.
belong to the class itself, and all instances of the class share one static
@@ -1028,12 +925,9 @@ class [extends BaseClassName] [implements listOfInterfaces] {
...
@@ -1028,12 +925,9 @@ class [extends BaseClassName] [implements listOfInterfaces] {
}
}
```
```
The extended class inherits fields and methods from the base class, but
The extended class inherits fields and methods from the base class, but not constructors, and can add its own fields and methods as well as override methods defined by the base class.
not constructors, and can add its own fields and methods as well as override
methods defined by the base class.
The base class is also called ‘parent class’ or ‘superclass’.
The base class is also called 'parent class' or 'superclass'. The extended class also called 'derived class' or 'subclass'.
The extended class also called ‘derived class’ or ‘subclass’.
Example:
Example:
...
@@ -1053,9 +947,7 @@ class Employee extends Person {
...
@@ -1053,9 +947,7 @@ class Employee extends Person {
}
}
```
```
A class containing the `implements` clause must implement all methods
A class containing the `implements` clause must implement all methods defined in all listed interfaces, except the methods defined with default implementation.
defined in all listed interfaces, except the methods defined with default
implementation.
```typescript
```typescript
interfaceDateInterface{
interfaceDateInterface{
...
@@ -1071,11 +963,9 @@ class MyDate implements DateInterface {
...
@@ -1071,11 +963,9 @@ class MyDate implements DateInterface {
### Access to Super
### Access to Super
The keyword `super` can be used to access instance fields, instance methods
The keyword `super` can be used to access instance fields, instance methods and constructors from the super class.
and constructors from the super class.
It is often used to extend basic functionality of subclass with the required
It is often used to extend basic functionality of subclass with the required behavior taken from the super class:
behavior taken from the super class:
```typescript
```typescript
classRectangle{
classRectangle{
...
@@ -1109,10 +999,8 @@ class FilledRectangle extends Rectangle {
...
@@ -1109,10 +999,8 @@ class FilledRectangle extends Rectangle {
### Override Methods
### Override Methods
A subclass can override implementation of a method defined in its superclass.
A subclass can override implementation of a method defined in its superclass.
An overridden method can be marked with the keyword `override` to improve
An overridden method can be marked with the keyword `override` to improve readability.
readability.
An overridden method must have the same types of parameters, and same or derived return type as the original method.
An overridden method must have the same types of parameters, and same or
derived return type as the original method.
```typescript
```typescript
classRectangle{
classRectangle{
...
@@ -1132,10 +1020,7 @@ class Square extends Rectangle {
...
@@ -1132,10 +1020,7 @@ class Square extends Rectangle {
### Method Overload Signatures
### Method Overload Signatures
A method can be specified to be called in different ways by writing overload
A method can be specified to be called in different ways by writing overload signatures. To do so, several method headers that have the same name but different signatures are written and immediately followed by the single implementation method.
signatures. To do so, several method headers that have the same name but
different signatures are written and immediately followed by the single
implementation method.
```typescript
```typescript
classC{
classC{
...
@@ -1150,13 +1035,11 @@ c.foo() // ok, 1st signature is used
...
@@ -1150,13 +1035,11 @@ c.foo() // ok, 1st signature is used
c.foo("aa")// ok, 2nd signature is used
c.foo("aa")// ok, 2nd signature is used
```
```
An error occurs if two overload signatures have the same name and identical
An error occurs if two overload signatures have the same name and identical parameter lists.
parameter lists.
## Constructors
## Constructors
A class declaration may contain a constructor that is used to initialize
A class declaration may contain a constructor that is used to initialize object state.
If no constructor is defined, then a default constructor with an empty
If no constructor is defined, then a default constructor with an empty parameter list is created automatically, for example:
parameter list is created automatically, for example:
```typescript
```typescript
classPoint{
classPoint{
...
@@ -1177,13 +1059,11 @@ class Point {
...
@@ -1177,13 +1059,11 @@ class Point {
letp=newPoint()
letp=newPoint()
```
```
In this case the default constructor fills the instance fields with
In this case the default constructor fills the instance fields with default values for the field types.
default values for the field types.
### Constructors in Derived Class
### Constructors in Derived Class
The first statement of a constructor body can use the keyword `super`
The first statement of a constructor body can use the keyword `super` to explicitly call a constructor of the direct superclass.
to explicitly call a constructor of the direct superclass.
```typescript
```typescript
classRectangle{
classRectangle{
...
@@ -1198,22 +1078,17 @@ class Square extends Rectangle {
...
@@ -1198,22 +1078,17 @@ class Square extends Rectangle {
}
}
```
```
If a constructor body does not begin with such an explicit call of a
If a constructor body does not begin with such an explicit call of a superclass constructor, then the constructor body implicitly begins with a superclass constructor call `super()`.
superclass constructor, then the constructor body implicitly begins
with a superclass constructor call `super()`.
### Constructor Overload Signatures
### Constructor Overload Signatures
A constructor can be specified to be called in different ways by writing
A constructor can be specified to be called in different ways by writing overload signatures. To do so, several constructor headers that have the same name but different signatures are written and immediately followed by the single implementation constructor.
overload signatures. To do so, several constructor headers that have the
same name but different signatures are written and immediately followed
@@ -1221,8 +1096,7 @@ let c1 = new C() // ok, 1st signature is used
...
@@ -1221,8 +1096,7 @@ let c1 = new C() // ok, 1st signature is used
letc2=newC("abc")// ok, 2nd signature is used
letc2=newC("abc")// ok, 2nd signature is used
```
```
An error occurs if two overload signatures have the same name and
An error occurs if two overload signatures have the same name and identical parameter lists.
identical parameter lists.
## Visibility Modifiers
## Visibility Modifiers
...
@@ -1236,18 +1110,16 @@ There are several visibility modifiers:
...
@@ -1236,18 +1110,16 @@ There are several visibility modifiers:
-`internal`.
-`internal`.
The default visibility is `public`.
The default visibility is `public`.
The modifier `internal` allows to limit visibility within
The modifier `internal` allows you to limit visibility within the current package.
the current package.
### Public Visibility
### Public Visibility
The `public` members (fields, methods, constructors) of a class are
The `public` members (fields, methods, constructors) of a class are visible in any part of the program, where their class is visible.
visible in any part of the program, where their class is visible.
### Private Visibility
### Private Visibility
A `private` member cannot be accessed outside the class it is declared in,
A `private` member cannot be accessed outside the class it is declared in.
for example:
Example:
```typescript
```typescript
classC{
classC{
...
@@ -1264,8 +1136,8 @@ c.y = "b" // compile-time error: 'y' is not visible
...
@@ -1264,8 +1136,8 @@ c.y = "b" // compile-time error: 'y' is not visible
### Protected Visibility
### Protected Visibility
The modifier `protected` acts much like the modifier `private`, but
The modifier `protected` acts much like the modifier `private`, but the `protected` members are also accessible in derived classes.
the `protected` members are also accessible in derived classes, for example:
Example:
```typescript
```typescript
classBase{
classBase{
...
@@ -1282,12 +1154,9 @@ class Derived extends Base {
...
@@ -1282,12 +1154,9 @@ class Derived extends Base {
## Object Literals
## Object Literals
An object literal is an expression that can be used to create a class instance
An object literal is an expression that can be used to create a class instance and provide some initial values. It can be used instead of the expression `new` as it is more convenient in some cases.
and provide some initial values. It can be used instead of the expression
`new` as it is more convenient in some cases.
A class composite is written as a comma-separated list of name-value pairs
A class composite is written as a comma-separated list of name-value pairs enclosed in '{' and '}'.
enclosed in ‘{’ and ‘}’.
```typescript
```typescript
classC{
classC{
...
@@ -1298,9 +1167,7 @@ class C {
...
@@ -1298,9 +1167,7 @@ class C {
letc:C={n:42,s:"foo"}
letc:C={n:42,s:"foo"}
```
```
Due to the static typing of the ArkTS, object literals can be used in a
Due to the static typing of the ArkTS, object literals can be used in a context where the class or interface type of the object literal can be inferred as in the example above. Other valid cases are illustrated below:
context where the class or interface type of the object literal can be
inferred as in the example above. Other valid cases are illustrated below:
An extended interface contains all properties and methods of the
An extended interface contains all properties and methods of the interface it extends, and can also add its own properties and methods.
interface it extends, and can also add its own properties and methods.
## Interface Visibility Modifiers
## Interface Visibility Modifiers
...
@@ -1474,13 +1335,11 @@ Only methods with default implementation can be defined as `private`.
...
@@ -1474,13 +1335,11 @@ Only methods with default implementation can be defined as `private`.
# Generic Types and Functions
# Generic Types and Functions
Generic types and functions allow creating the code capable to work over a
Generic types and functions allow creating the code capable to work over a variety of types rather than a single type.
variety of types rather than a single type.
## Generic Classes and Interfaces
## Generic Classes and Interfaces
A class and an interface can be defined as generics, adding parameters to the
A class and an interface can be defined as generics, adding parameters to the type definition, like the type parameter `Element` in the following example:
type definition, like the type parameter `Element` in the following example:
```typescript
```typescript
classStack<Element>{
classStack<Element>{
...
@@ -1510,9 +1369,7 @@ s.push(55) // That will be a compile-time error
...
@@ -1510,9 +1369,7 @@ s.push(55) // That will be a compile-time error
## Generic Constraints
## Generic Constraints
Type parameters of generic types can be bounded. For example, the `Key`
Type parameters of generic types can be bounded. For example, the `Key` type parameter in the `HashMap<Key, Value>` container must have a hash method, that is, it must be hashable.
type parameter in the `HashMap<Key, Value>` container must have a hash
method, i.e., it must be hashable.
```typescript
```typescript
interfaceHashable{
interfaceHashable{
...
@@ -1526,13 +1383,11 @@ class HasMap<Key extends Hashable, Value> {
...
@@ -1526,13 +1383,11 @@ class HasMap<Key extends Hashable, Value> {
}
}
```
```
In the above example, the `Key` type extends `Hashable`, and all methods
In the above example, the `Key` type extends `Hashable`, and all methods of `Hashable` interface can be called for keys.
of `Hashable` interface can be called for keys.
## Generic Functions
## Generic Functions
Use a generic function to create a more universal code. Consider a function
Use a generic function to create a more universal code. Consider a function that returns the last element of the array:
that returns the last element of the array:
```typescript
```typescript
functionlast(x:number[]):number{
functionlast(x:number[]):number{
...
@@ -1541,8 +1396,7 @@ function last(x: number[]): number {
...
@@ -1541,8 +1396,7 @@ function last(x: number[]): number {
console.log(last([1,2,3]))// output: 3
console.log(last([1,2,3]))// output: 3
```
```
If the same function needs to be defined for any array, then define it as
If the same function needs to be defined for any array, then define it as a generic with a type parameter:
Programs are organized as sets of compilation units or modules.
Programs are organized as sets of compilation units or modules.
Each module creates its own scope, i.e., any declarations (variables,
Each module creates its own scope, i.e., any declarations (variables, functions, classes, etc.) declared in the module are not visible outside that module unless they are explicitly exported.
functions, classes, etc.) declared in the module are not visible outside
that module unless they are explicitly exported.
Conversely, a variable, function, class, interface, etc. exported from
Conversely, a variable, function, class, interface, etc. exported from another module must first be imported to a module.
another module must first be imported to a module.
## Export
## Export
A top-level declaration can be exported by using the keyword `export`.
A top-level declaration can be exported by using the keyword `export`.
A declared name that is not exported is considered private and can be used
A declared name that is not exported is considered private and can be used only in the module where it is declared.
only in the module where it is declared.
```typescript
```typescript
exportclassPoint{
exportclassPoint{
...
@@ -1733,20 +1571,17 @@ export function Distance(p1: Point, p2: Point): number {
...
@@ -1733,20 +1571,17 @@ export function Distance(p1: Point, p2: Point): number {
## Import
## Import
Import declarations are used to import entities exported from other modules
Import declarations are used to import entities exported from other modules and provide their bindings in the current module.
and provide their bindings in the current module. An import declaration
An import declaration consists of two parts:
consists of two parts:
* Import path that determines the module to import from;
* Import path that determines the module to import from.
* Import bindings that define the set of usable entities in the imported
* Import bindings that define the set of usable entities in the imported module, and the form of use (i.e., qualified or unqualified use).
module, and the form of use (i.e., qualified or unqualified use).
Import bindings may have several forms.
Import bindings may have several forms.
Let’s assume a module has the path ‘./utils’ and export entities ‘X’ and ‘Y’.
Let's assume a module has the path './utils' and export entities 'X' and 'Y'.
An import binding of the form `* as A` binds the name ‘A’, and all entities
An import binding of the form `* as A` binds the name 'A', and all entities exported from the module defined by the import path can be accessed by using
exported from the module defined by the import path can be accessed by using
the qualified name `A.name`:
the qualified name `A.name`:
```typescript
```typescript
...
@@ -1755,8 +1590,7 @@ Utils.X // denotes X from Utils
...
@@ -1755,8 +1590,7 @@ Utils.X // denotes X from Utils
Utils.Y// denotes Y from Utils
Utils.Y// denotes Y from Utils
```
```
An import binding of the form `{ ident1, ..., identN }` binds an exported
An import binding of the form `{ ident1, ..., identN }` binds an exported entity with a specified name, which can be used as a simple name:
entity with a specified name, which can be used as a simple name:
```typescript
```typescript
import{X,Y}from"./utils"
import{X,Y}from"./utils"
...
@@ -1764,8 +1598,7 @@ X // denotes X from Utils
...
@@ -1764,8 +1598,7 @@ X // denotes X from Utils
Y// denotes Y from Utils
Y// denotes Y from Utils
```
```
If a list of identifiers contains aliasing of the form `ident as alias`,
If a list of identifiers contains aliasing of the form `ident as alias`, then entity `ident` is bound under the name `alias`:
then entity `ident` is bound under the name `alias`:
```typescript
```typescript
import{XasZ,Y}from"./utils"
import{XasZ,Y}from"./utils"
...
@@ -1778,17 +1611,13 @@ X // Compile-time error: 'X' is not visible
...
@@ -1778,17 +1611,13 @@ X // Compile-time error: 'X' is not visible
A module can contain any statements at the module level, except `return` ones.
A module can contain any statements at the module level, except `return` ones.
If a module contains a `main` function (program entry point), then
If a module contains a `main` function (program entry point), then top-level statements of the module are executed immediately before the body of this function.
top-level statements of the module are executed immediately before
Otherwise, they are executed before execution of any other function of the module.
the body of this function.
Otherwise, they are executed before execution of any other function
of the module.
## Program Entry Point
## Program Entry Point
An entry point of a program (application) is the top-level `main` function.
An entry point of a program (application) is the top-level `main` function.
The `main` function must have either an empty parameter list or a single
The `main` function must have either an empty parameter list or a single parameter of `string[]` type.
parameter of `string[]` type.
```typescript
```typescript
functionmain(){
functionmain(){
...
@@ -1798,18 +1627,11 @@ function main() {
...
@@ -1798,18 +1627,11 @@ function main() {
# Support for ArkUI
# Support for ArkUI
This section demonstrates mechanisms that ArkTS provides for
This section demonstrates mechanisms that ArkTS provides for creating graphical user interface (GUI) programs. The section is based on the ArkUI declarative framework. ArkUI provides a set of extensions of the standard TypeScript to declaratively describe the GUI of the applications and the interaction between the GUI components.
creating graphical user interface (GUI) programs. The section is based on
the ArkUI declarative framework. ArkUI provides a set of extensions of
the standard TypeScript to declaratively describe the GUI of the applications
and the interaction between the GUI components.
## ArkUI Example
## ArkUI Example
The following example provides a complete ArkUI-based application as an
The following example provides a complete ArkUI-based application as an illustration of GUI programming capabilities. For more details of the ArkUI features, refer to the ArkUI [tutorial](arkts-get-started.md).
illustration of GUI programming capabilities. For more details of the