HarmonyOS development: ArkTs data type

AbnerMingAbnerMing
10 min read

Foreword

this article code case based on api13.

Data type is the most common in development. No matter which language it is, it is always dealing with it. It is a mechanism used in programming language to define variables, function return values, data structures, etc. that can store data types and ranges. It is also an abstract representation of data in memory by programming language. It is precisely because of data types, it enables programmers to write code in a clearer and easier-to-understand manner, while ensuring data correctness and security.

Regardless of the programming language, the representation of data types may be different, but it can basically be divided into two types, one is the basic data type, and the other is the data type.

Basic data type

in ArkTs, there are two used to represent basic data types, one is the number type, the other is Boolean.

number type: used to represent integers, floating-point , which can represent positive, negative, or zero, as well as single and double precision floating points.

Boolean type: used to represent logical True and False. The Boolean type has only two values and is usually used for conditional judgments and logical operations.

Composite data type

composite data types are relatively large, such as strings, arrays, objects, enumerations, etc., as follows:

string: A sequence of characters used to represent text data. The characters in the string can be letters, numbers, symbols, or spaces.

Array: A collection of elements of the same data type. The elements in the array can be accessed by Index, which is usually an integer starting from 0.

Class: Used to represent a complex data structure that can contain many different types of member variables (properties) and member functions (methods). Classes are very important in object-oriented programming.

Union: Allows you to store different types of data in the same memory location, but only one type of data at a time. Union types are common in embedded programming and system-level programming.

Enums: Give friendly names to integer constants to make the code clearer and easier to understand. Enumeration types are useful when defining a finite set of constants.

Function type: indicates the signature of the function, including the return type and parameter type of the function. Function types are common in functional programming and high-level programming languages.

It should be noted that different programming languages may support different data types, and the implementation and restrictions of the same data type may vary in different programming languages.

The data types are summarized as follows:

data Type

overview

number

numerical

boolean

boolean

string

string

void

type without any return value

Object

Object

array

array

enum

enumeration

Union

joint Type

Aliases

anonymous type

undefined

an undefined or non-existent value

null

empty

never

types that never exist

1 Type of number

in ArkTs, it is not as strict as Java language, int is int,float is float, it covers a lot, any integer and floating point number can be assigned to this type of variable, we collectively referred to as digital literal, and digital literal is divided into Integer literal and decimal floating point literal.

Integer literals include the following categories:

1. A decimal integer consisting of a sequence of numbers. For example: 6, 88, -88

A hexadecimal integer beginning with 0x (or 0X) that can contain numbers (0-9) and letters a-f or A- F. For example: 0x22b8, 0x 00111, -0xF1A7

3. An octal integer starting with 0o (or 0O) can only contain digits (0-7). For example: 0o21270

4. A binary integer starting with 0b (or 0B) can only contain the digits 0 and 1. For example: 0b10001010111000, 0b0011, -0b11

floating-point literals include the following:

1, decimal integer, can be a signed number (that is, the prefix is "+" or "-");

2. Decimal point (".")

3, decimal part (represented by a decimal number string)

an exponent part that begins with "e" or "E", followed by a signed (I. e., prefixed with "+" or "-") or unsigned integer.

Code example:

let a = 8 //
let b = 8.88 //
let c = -888 //
let d = 0x22b8 // 
let e = 0o21270 // 
let f = 0b10001010111000 //
let g = 8e2

there is a problem that needs to be noted. The number type will cause precision loss when representing large integers. The bigInt type can be used as needed to ensure precision during development:

let bigInt: BigInt = BigInt('88888888888888888888888888888888888888888888888')
console.log("bigInt:" + bigInt.toString())

2. boolean type

indicates a logical value of true or false, mainly used for conditional judgment.

Code example:

let isCompleted: boolean = false

if (isCompleted) {
  console.log ('Completed')
}

3. string type

string type data is the most common in development. It represents a sequence of characters and can be used to represent characters. Since this section is very important, we will focus on the following section. At present, we will first understand the string type.

A string literal consists of zero or more characters enclosed in single quotation marks (') or double quotation marks ("). String literals also have a special form, which is a template literal enclosed in Reverse single quotes (').

let s1 = 'Hello, world!\n';
let s2 = 'this is a string';
let a = 'Success';
let s3 = `The result is ${a}`;

4. void type

the void type specifies that the function does not return a value.

This type has only one value, which is also void, and because void is a reference type, it can be used for generic type parameters.

class Class<T> {
  //...
}
let instance: Class <void>

5. Object Type

the Object type is the base type of all reference types, and any value, including values of basic types (which are automatically boxed), can be assigned directly to a variable of type Object.

let a: Object = 8 //int
let b: Object = true //boolean
let c: Object = "字符串" //string

However, one thing to note is that lowercase there is a difference between object and uppercase Object, that is, the object type is mainly used to represent types other than the basic type. If the above code is represented by object, an exception will be reported.

6. array type

array, or array, is also a very important data type, and will be highlighted in the following chapters.

Arrays can be assigned by an array compound literal (that is, a list of zero or more expressions enclosed in square brackets, where each expression is an element in the array). The length of an array is determined by the number of elements in the array. The index of the first element in the array is 0.

Arrays in ArkTs are special. If you are not sure about the relevant type, its elements can be of multiple types. The following code contains an array of three elements.

let value = ['string', 88, true]

In actual development, for the sake of type accuracy, it is recommended that you set the relevant type directly:

let value:string[] = ['string', 'string2', 'string3']

7. Type of enum

the enum type, also known as an enumeration type, is a value type with a predefined set of named values, which are also called enumeration constants.

Enumeration constants must be prefixed with the enumeration type name.

enum ColorSet { 
  Red, Green, Blue 
}
let c: ColorSet = ColorSet.Red

A constant expression can be used to explicitly set the value of an enumeration constant.

enum ColorSet { 
  White = 0xFF, Grey = 0x7F, Black = 0x00 
}
let c: ColorSet = ColorSet.Black

8. Union type

union type, that is, union type, is a reference type composed of multiple types. union type contains all possible types of variables. This is very common in system APIs. For example, the size parameter of text is a union type.

Code example:

class Cat {
  name: string = 'cat';
  // ...
}
class Dog {
  name: string = 'dog';
  // ...
}
class Frog {
  name: string = 'frog';
  // ...
}

type Animal = Cat | Dog | Frog | number




let animal: Animal = new Cat()
animal = new Frog()
animal = 42;

different mechanisms can be used to obtain the value of a particular type in a Union type.

Example:

class Cat { 
  sleep () {

  }
  meow () {

  } 
}
class Dog { 
  sleep () {

}
  bark () {

} 
}
class Frog { 
  sleep () {

  }
  leap () {

  } 
}


type Animal = Cat | Dog | Frog;


function foo(animal: Animal) {
  if (animal instanceof Frog) {
    animal.leap()  
  }
  animal.sleep() 
}

9. Types of Aliases

the Aliases type provides names for anonymous types (arrays, functions, object literals, or union types), or alternative names for existing types.

type Matrix = number[][];
type Handler = (s: string, no: number) => string;
type Predicate <T> = (x: T) => boolean;
type NullableObject = Object | null;

undefined or non-existent values

when you define a variable and assign a value, then it is undefined, although it can be set directly. The undefined type, under normal circumstances undefined is not used alone because of the subsequent assignment problem.

 let test:undefined

Although the above code will not cause problems, it is meaningless. In general, it can appear as a joint type, as follows:

let test: undefined | number
test = 0

of course, more is the use of member variables, as shown below, with a question mark, which means that this attribute can be undefined.

test?:number

Then in future development, if you are not sure whether a data has a value, whether object or other types, you can make undefined judgment:

if (test != undefined) {
  console.log("yes")
} else {
  console.log("no")
}

11, empty null

null is an object representing "null value", which is usually used to represent that the value of a variable is "no value". If you need to explicitly represent that the value of a variable is null, you can use null, which is similar to undefined. Generally, it is not used directly and can be used in combination with other types.


let test: null | number
test = 0

In addition to the default value of the variable assigned to null, it can also be used as the return value of the function. When the function does not need to return a value, return null can be used to indicate that the return value of the function is empty.

Comparison between null and undefined

1. null means that the object is empty, while undefined means that the value is missing.

2. When a variable is declared but not assigned, the value of the variable is undefined. When a null value is required, null can be used.

3. When comparing, the values of null and undefined are equal, but the data types are different.

The type never exists.

The never type is rarely encountered in development. It is a subtype of any type and can be assigned to any type. However, it is important to know that never has no subtype.

The never type is generally the return type of a function expression or arrow function expression that always throws an exception or does not return a value at all, as shown in the following example:


  error(message: string): never {
    throw new Error(message);
  }


  infiniteLoop(): never {
    while (true) {
    }
  }

summary

regardless of the type, if it is a member variable, the type and question mark need to be added if there is no default value, as shown in the following code:

  test?: number

Another point is better, that is, ArkTs and also have type inference function. Types can be written without errors. In order to avoid redundancy, it is also recommended to discard types in future writing, provided there is a default value.

let test = 0

In some scenarios, especially for union types, we need to determine which type of the current attribute is. We can use the typeof keyword to determine, for example, the following:

let a = 1
let type = typeof a

finally, ArkTS does not support any and unknown types. You need to explicitly specify the specific type, otherwise an exception will be reported. The specific reason is that this is ArkTS one of the features of is the use of static typing; If the program is statically typed, I .e., all types are known at compile time, then the developer can easily understand which data structures are used in the code. At the same time, because all types are known before the program actually runs, the compiler can verify the correctness of the code in advance, which can reduce runtime type checks and help improve performance.

0
Subscribe to my newsletter

Read articles from AbnerMing directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

AbnerMing
AbnerMing