Types constrain the possible values and operations of variables, parameters, and return values. ArkTS strengthens static checking and null safety on top of TypeScript's type system. This topic describes built-in and custom types, differences between value and reference types, utility types, subtype relationships, the benefits of type safety, type guards, and type assertions.
Built-in types are predefined by the language and can be used without importing them. ArkTS provides the following built-in types:
| Type | Description |
|---|---|
| number | Numeric values, with a unified representation for integers and floating-point numbers |
| boolean | Logical values: true or false |
| string | Strings |
| bigint | Arbitrary-precision integers |
| void | No function return value |
| null / undefined | Null / undefined values |
| Literal types | Specific literal values used as types |
| object / Object | Non-primitive types / root type of all non-null types |
| never | Values that never occur, such as the return value of a function that always throws |
number represents IEEE 754 double-precision floating-point numbers (64-bit), with no separate integer type. It supports decimal, hexadecimal, binary, and octal literals. boolean represents logical values produced by comparison and logical operations. To avoid JavaScript type confusion, ArkTS prohibits implicit conversions between boolean and other types in assignments, argument passing, and similar contexts. Template literal interpolation (such as ${true}) converts a Boolean to a string for output and is not the implicit conversion discussed here. Use Boolean expressions directly in conditions; do not mix Boolean values with other types. string represents strings. For details, see Strings.
// number: unified representation for integers and floating-point numbers. let age: number = 25; let price: number = 9.99; let hex: number = 0xFF; // Hexadecimal literal. // boolean: logical values. let enabled: boolean = true; // string: strings. let appName: string = 'ArkTS';
The bigint type represents arbitrary-precision integers. Literals have an n suffix and support very large integer calculations: bigValue stores a very large integer without losing precision, and nextValue adds to it precisely. bigint and number cannot be mixed directly in arithmetic; use BigInt() for explicit conversion. This type supports integer arithmetic only, not fractional values.
let bigValue: bigint = 999999999999999999999999999999999999n;
console.info(`${bigValue.toString()}`);
let nextValue: bigint = bigValue + 1n;
console.info(`${nextValue.toString()}`); let bigintCount: number = 10; let preciseCount: bigint = BigInt(bigintCount); let total: bigint = preciseCount + 20n;
Some APIs (such as Date methods) or annotation fields may not support bigint. Check the type constraints in the relevant API documentation before use. Prefer bigint for large integers to avoid precision loss with number.
void indicates that a function has no return value and is used for functions that perform operations without returning results. It differs from undefined: the former describes a function return type, while the latter represents an undefined value.
function log(message: string): void {
console.info(`${message}`);
} null represents an intentionally assigned null value, while undefined indicates an unassigned variable or a missing property. Distinguish these meanings explicitly. Prefer undefined for an absent value and use null only when null semantics are explicitly needed. ArkTS enables null safety by default: null and undefined cannot be assigned to non-nullable types (let name: string = null is a compilation error). Before accessing nullable values, use a null check, optional chaining (?.), or nullish coalescing (??). For details, see Basic Operators.
// null: explicitly indicate a null value.
let nickname: string | null = null;
// undefined: an undefined value; an optional property's implicit type is T | undefined.
interface NullableUserProfile {
name: string;
email?: string;
}
let nullableUser: NullableUserProfile = { name: 'Alice' }; // number: unified representation for integers and floating-point numbers. let empty: null = null; let nullUndefData: string | null = null; // boolean: logical values. let missing: undefined = undefined; let optional: string | undefined = undefined; // string: strings. let nickname: string | null = null; // Explicitly indicates no nickname. let title: string | undefined; // May not be provided.
Nullable types (T | null/T | undefined) and optional properties both express that a value may be absent. ? is a property declaration modifier (name?: string), whereas a nullable type is an explicit union type annotation (name: string | null).
A literal type uses a value itself as a type, restricting a variable to a specific literal value. It is often combined with union types to constrain the range of values. Constants declared with const are inferred as literal types (for example, const pi = 3.14 is inferred as 3.14).
type TaskState = 'pending' | 'running' | 'done'; let state: TaskState = 'pending'; // state = 'finished'; // Compilation error: 'finished' is not a member of TaskState. // Constants declared with const are inferred as literal types. const pi = 3.14; // Inferred as the literal type 3.14. let piValue: number = pi; // A literal type can be assigned to number.
object represents non-primitive types, including reference types such as objects, arrays, and class instances. Object is the root type of all non-null types: any value other than null or undefined can be assigned to an Object variable. Variables of type object or Object can access only members common to all types; narrow the type or use an assertion before accessing specific members. In addition, object literals cannot directly initialize Object or object variables and must correspond to an explicitly declared class or interface. For details, see TypeScript to ArkTS Cookbook.
interface Point {
x: number;
y: number;
}
// object: non-primitive types.
let point: Point = { x: 1, y: 2 };
let ref: object = point;
// Object: root type of all non-null types.
let boxed: Object = 'hello';
let boxedObj: Object = point;
// Narrow an Object value before accessing specific members.
if (typeof boxed === 'string') {
console.info(`${boxed.length}`); // 5
} The never type represents values that never occur. It is commonly used as the return type of functions that always throw exceptions or loop indefinitely.
function fail(message: string): never {
throw new Error(message);
}
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${value}`);
}
interface NevCircle {
kind: 'circle';
radius: number;
}
interface NevSquare {
kind: 'square';
sideLength: number;
}
type NevShape = NevCircle | NevSquare;
function nevShapeArea(shape: NevShape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius * shape.radius;
case 'square':
return shape.sideLength * shape.sideLength;
default:
// Compilation fails here if a new union member is not covered by a case.
const _check: never = shape;
return _check;
}
} never is commonly used for functions that always throw and never return, and for exhaustiveness checks. In the default branch of a switch, assign the discriminated value to a never variable (for example, const _check: never = value;), or pass it to a function such as assertNever whose parameter type is never. If the cases do not cover all union members, the value cannot be assigned to never, and the compiler reports an error, ensuring exhaustive coverage.
For details about declaring, iterating over, and working with arrays (T[]), which are built-in reference types, see Collection Types.
Combine built-in types or declare new types to model business requirements. A type alias (type) gives a new name to any type and is often used with union and function types. Classes, interfaces, and enums have dedicated topics; only simple examples are provided here.
A type alias uses type to give an existing type a new name without creating a new type. It commonly gives meaningful names to complex types such as unions and function types, or business-specific names to primitive types.
// Alias a primitive type to clarify its meaning.
type AccountId = number;
let accountId: AccountId = 1001;
// Alias a union of literal types to constrain possible values.
type SortOrder = 'asc' | 'desc';
let order: SortOrder = 'asc';
console.info(`${accountId}`); // 1001
console.info(`${order}`); // 'asc' A union type represents a value that can be one of several types separated by a vertical bar (|). Only members common to all constituent types can be accessed directly. To access type-specific members, first narrow the type with a type guard (see Type Guards). Nullable types (T | null) and optional properties (prop?: T, equivalent to T | undefined) are common uses of union types.
type ID = string | number;
let userId: ID = 'A-001';
userId = 100; // Can also be a number.
function printId(id: ID): void {
if (typeof id === 'string') {
console.info(`${id.toUpperCase()}`); // string-specific member.
} else {
console.info(`${id.toFixed(0)}`); // number-specific member.
}
} A function type describes a function signature in the form (parameterList) => ReturnType. Functions can be assigned to variables and passed as arguments. For details, see Functions.
type Comparator = (a: number, b: number) => number;
let ascending: Comparator = (a: number, b: number): number => {
return a - b;
};
console.info(`${ascending(3, 1)}`); // 2 An enum type defines a set of named constant values, making fixed states easier to express meaningfully.
enum MyColor {
Red,
Green,
Blue
}
let favorite: MyColor = MyColor.Blue; For details, see Enums.
An interface defines an object's structural contract, describing property names, types, and optionality.
interface MyPosition {
x: number;
y: number;
}
let origin: MyPosition = { x: 0, y: 0 }; For details, see Interfaces.
A class defines both data structure and behavior and is the only custom type whose instances can be created with new.
class MyRectangle {
public width: number;
public height: number;
constructor(width: number, height: number) {
this.width = width;
this.height = height;
}
public getArea(): number {
return this.width * this.height;
}
}
let rect: MyRectangle = new MyRectangle(3, 4);
console.info(`${rect.getArea()}`); // 12 For details, see Classes.
ArkTS types fall into two categories by memory allocation and access. Value types (primitive types such as number, boolean, string, null, and undefined) store values directly, and assignment copies the values themselves. Reference types (objects, arrays, class instances, functions, and so on) store object references; assignment copies the reference, so multiple variables point to the same object.
After value-type assignment, the two variables are independent: modifying one does not affect the other. After reference-type assignment, they share the same object.
// Value type: assignment copies the value; the two variables are independent.
let countA: number = 10;
let countB: number = countA;
countB = 20;
console.info(`${countA}`); // 10 (unaffected by countB)
// Reference type: assignment copies the reference; both variables point to the same object.
interface Score {
value: number;
}
let scoreA: Score = { value: 90 };
let scoreB: Score = scoreA;
scoreB.value = 95;
console.info(`${scoreA.value}`); // 95 (scoreA also changes) Changes to object state through any reference are visible through all references to that object. The same applies to function arguments: for reference types, changes inside the function affect the original object's state; for value types, the function operates only on a copy and does not affect the external variable. To copy an object instead of sharing a reference, use a shallow or deep copy. For details, see Classes.
class Task {
public status: string = 'pending';
}
// Reference-type parameter: modify the original object's state inside the function.
function start(task: Task): void {
task.status = 'running';
}
let myTask: Task = new Task();
start(myTask);
console.info(`${myTask.status}`); // running (original object modified)
// Value-type parameter: modify only a copy inside the function.
function double(value: number): number {
value = value * 2; // Modify only the copy.
return value;
}
let count: number = 10;
double(count);
console.info(`${count}`); // 10 (unchanged) ArkTS supports a small set of utility types for transforming existing types: only Partial<T>, Required<T>, Readonly<T>, and Record<K, V>. Other utility types, such as Pick<T, K> and Omit<T, K>, are not supported.
Partial<T> makes all properties of T optional and suits objects representing partial updates. Required<T> makes all properties of T required. The generic argument T of Partial<T> must be a class or interface type.
interface UserProfile {
id: number;
name: string;
email: string;
}
// Partial<T>: make all properties optional.
let patch: Partial<UserProfile> = { name: 'Alice' };
interface PageQuery {
keyword?: string;
pageSize?: number;
}
// Required<T>: make all properties required.
let strictQuery: Required<PageQuery> = { keyword: 'arkts', pageSize: 20 }; Readonly<T> makes all properties of T read-only, preventing changes after initialization. Individual read-only class properties can also be declared with readonly.
interface AppConfig {
appId: string;
version: string;
}
let config: Readonly<AppConfig> = { appId: 'com.example.app', version: '1.0.0' };
// config.version = '1.0.1'; // Compilation error: the property is read-only. Record<K, V> maps key type K to value type V and suits key-value structures. The key type K can only be string or number. Indexed access to a Record object's value produces a union type that includes undefined. For more uses of Record, see Collection Types.
interface CityInfo {
country: string;
population: number;
}
let cityMap: Record<string, CityInfo> = {
'Beijing': { country: 'China', population: 21860000 }
};
let info: CityInfo | undefined = cityMap['Beijing']; // The indexed access result includes undefined. TypeScript type operations such as intersection types, conditional types, mapped types, and indexed access types (T[K]) are not supported in ArkTS. In generic scenarios, prefer explicit interfaces, classes, or generic constraints to describe structures. For details, see Generics.
If any value of type S can be safely assigned to a variable of type T, S is a subtype of T. ArkTS does not support structural typing (duck typing): the compiler does not determine compatibility by comparing type structures. Subtype relationships are based on explicit inheritance and implements relationships.
A subclass is a subtype of its parent class. A subclass instance can be implicitly assigned to a parent-type variable (upcasting), after which only members declared in the parent are accessible. Assigning a parent-type variable to a subclass variable (downcasting) is not type-safe. Within an instanceof guard, the variable is automatically narrowed to the subtype and can be assigned directly (see below). Outside the guard, an as assertion is required; first checking the actual type with instanceof is recommended.
class Creature {
public name: string;
constructor(name: string) {
this.name = name;
}
public speak(): void {
console.info(`${this.name} makes a sound`);
}
}
class Hound extends Creature {
public breed: string;
constructor(name: string, breed: string) {
super(name);
this.breed = breed;
}
public bark(): void {
console.info(`${this.name} barks: Woof!`);
}
}
// Upcasting: implicitly assign a subclass instance to a parent-type variable.
let hound: Hound = new Hound('Buddy', 'Golden Retriever');
let creature: Creature = hound;
creature.speak(); // 'Buddy makes a sound'
// creature.bark(); // Compilation error: a parent-type variable cannot access subclass-specific members.
// Downcasting: check the actual type first.
if (creature instanceof Hound) {
let myHound: Hound = creature; // Automatically narrowed within the guarded branch.
myHound.bark(); // 'Buddy barks: Woof!'
} The same applies to implementing classes and interfaces: an instance of a class that declares implements can be implicitly assigned to an interface-type variable; the reverse requires an assertion.
Assigning a function to a function-type variable must satisfy function subtyping rules: the source function can have fewer parameters, but not more; its parameter types can be supertypes of the target parameter types (parameter contravariance); its return type must be a subtype of the target return type (return type covariance).
class BaseType {}
class SubType extends BaseType {}
// Target function type: (SubType) => BaseType
type Handler = (input: SubType) => BaseType;
// Supertype parameter (contravariance) and subtype return value (covariance) satisfy subtyping rules.
let handler: Handler = (input: BaseType): SubType => {
return new SubType();
};
// A function with fewer parameters can be assigned to a function type with more parameters.
type BinaryOp = (a: number, b: number) => number;
let doubleFn: BinaryOp = (a: number): number => a * 2; Each constituent type of a union is a subtype of that union, so both string and number values can be assigned to a string | number variable. Conversely, a union is not a subtype of its constituents: a string | number value cannot be assigned to a string variable.
type Identifier = string | number; // Both string and number are subtypes of Identifier. let id: Identifier = 'A-001'; id = 100; let displayName: string = 'Alice'; id = displayName; // OK: string is a subtype of string | number. // displayName = id; // Compilation error: string | number is not a subtype of string.
Type safety catches type errors at compile time, reducing runtime problems that are difficult to diagnose. The compiler rejects assignments with mismatched types (such as assigning string to a number variable) and calls with mismatched types, so you can find errors without waiting for runtime.
let typeCheckAge: number = 25;
typeCheckAge = 'text'; // Compilation error: type mismatch.
function typeCheckAdd(a: number, b: number): number {
return a + b;
}
typeCheckAdd(1, 2); // Correct
typeCheckAdd(1, '2'); // Compilation error Type safety detects errors early at compile time and prevents runtime crashes. It also improves code readability and refactoring safety and supports intelligent suggestions in DevEco Studio.
Type guards check a value's actual type at runtime and narrow a union to a specific type at compile time. In a branch where the guard holds, type-specific members can be accessed directly without an assertion. Unlike assertions, guards perform actual runtime checks and provide a safer way to narrow types.
The compiler tracks type changes along control flow branches such as if/else, switch, and loops. It narrows variables to more specific types within branches and takes their union when branches merge. The typeof and instanceof guards described below rely on this mechanism.
let tiValue: string | number = 'hello';
if (typeof tiValue === 'string') {
console.info(tiValue.toUpperCase()); // tiValue is narrowed to string here.
} else {
console.info(`${tiValue}`); // tiValue is narrowed to number here.
} typeof checks basic types and commonly narrows unions of primitive types such as string, number, and boolean.
function typeGuardProcessValue(value: string | number | boolean): void {
if (typeof value === 'string') {
// The compiler knows value is a string.
console.info(`String length: ${value.length}`);
console.info(`Uppercase: ${value.toUpperCase()}`);
} else if (typeof value === 'number') {
// The compiler knows value is a number.
console.info(`Number: ${value.toFixed(2)}`);
console.info(`Square: ${value * value}`);
} else if (typeof value === 'boolean') {
// The compiler knows value is a boolean.
console.info(`Boolean: ${value ? 'True' : 'False'}`);
}
}
typeGuardProcessValue('Hello'); // Output two lines: String length: 5 / Uppercase: HELLO
typeGuardProcessValue(42); // Output two lines: Number: 42.00 / Square: 1764
typeGuardProcessValue(true); // Boolean: True instanceof checks whether an object is an instance of a class by matching along the prototype chain. Within a guarded branch, it narrows the type to that class, allowing safe access to class-specific members. It is also commonly used to check the actual type before downcasting (see Subtyping).
class TypeGuardDog {
public name: string;
constructor(name: string) {
this.name = name;
}
public bark(): void {
console.info(`${this.name} barks: Woof!`);
}
}
class Cat {
public name: string;
constructor(name: string) {
this.name = name;
}
public meow(): void {
console.info(`${this.name} meows: Meow!`);
}
}
function makeSound(pet: TypeGuardDog | Cat): void {
console.info(`Pet name: ${pet.name}`);
if (pet instanceof TypeGuardDog) {
// The compiler knows pet is a TypeGuardDog.
pet.bark();
} else if (pet instanceof Cat) {
// The compiler knows pet is a Cat.
pet.meow();
}
}
let myDog = new TypeGuardDog('Buddy');
let myCat = new Cat('Whiskers');
makeSound(myDog); // Pet name: Buddy, Buddy barks: Woof!
makeSound(myCat); // Pet name: Whiskers, Whiskers meows: Meow! A type assertion tells the compiler to treat a value as a specified type. In ArkTS, as is the only type assertion syntax (value as Type); the angle-bracket syntax <Type>value is not supported. For potentially nullish values, the non-null assertion operator (!) asserts that the value is neither null nor undefined. For its usage and restrictions, see Non-Null Assertion Operator.
Assertions are commonly used for downcasting from a supertype to a subtype or treating a broadly typed value as a specific type.
interface UserInfo {
id: number;
name: string;
}
let user: UserInfo = { id: 1, name: 'Alice' };
// Upcasting: implicit conversion from subtype to supertype.
let obj: Object = user;
// Downcasting: use an as assertion from supertype to subtype.
let restored: UserInfo = obj as UserInfo;
console.info(`${restored.name}`); // 'Alice'
// Assert a union type.
let mixed: Object = 42;
let unionValue: number | string = mixed as number | string; A type assertion does not change the value itself; it only treats it as the target type. Data conversion, such as Number() or String(), actually changes the value's type at runtime. To change a data type, use a conversion function, not an assertion.
let convValue: Object = '123';
// Type assertion: keep the value unchanged and treat it as the target type.
let text: string = convValue as string; // The runtime value is a string, so the assertion succeeds.
console.info(`${text.length}`); // 3
// Data conversion: actually convert the data type at runtime.
let num: number = Number('123');
console.info(`${num.toFixed(2)}`); // 123.00 Type assertions have two constraints. At compile time, assertions between unrelated types are prohibited. At runtime, if the asserted type does not match the actual type, accessing methods specific to the target type causes a runtime error, while property access returns undefined. Prefer type guards for narrowing, since guarded branches need no assertions. If an assertion is necessary, first ensure that the actual type matches the asserted type.
class ShapeBase {
public name: string = 'shape';
}
class RoundShape extends ShapeBase {
public draw(): void {
console.info(`draw ${this.name}`);
}
}
let checkShape: ShapeBase = new ShapeBase();
let wrongCircle: RoundShape = checkShape as RoundShape;
// wrongCircle.draw(); // Runtime error: calling a RoundShape member fails the runtime type check.
// Correct approach: check the actual type before access.
if (checkShape instanceof RoundShape) {
checkShape.draw();
}