21. ArkTS-TypeScript compatibility

This section discusses all issues related to different compatibility aspects between ArkTS and TypeScript.

21.1. Undefined is Not a Universal Value

ArkTS raises a compile-time or a runtime error in many cases, in which TypeScript uses undefined as runtime value.

1 let array = new Array<number>
2 let x = array [1234]
3    // |TS|: x will be assigned with undefined value !!!
4    // |LANG|: compile-time error if analysis may detect array out of bounds
5    //         violation or runtime error ArrayOutOfBounds
6 console.log(x)

21.2. Numeric Semantics

TypeScript has a single numeric type number that handles both integer and real

numbers.

ArkTS interprets number as a variety of ArkTS types depending on the

context, and calculations can produce different results:

1 let n = 1
2    // |TS|: treats 'n' as having type number
3    // |LANG|: treats 'n' as having type int to reach max code performance
4
5
6 console.log(n / 2)
7    // |TS|: will print 0.5 - floating-point division is used
8    // |LANG|: will print 0 - integer division is used

21.3. Covariant Overriding

TypeScript if non-existing property is accessed from some object during program

execution TypeScript runtime may handle such situations due to its object runtime model.

ArkTS allows to generate high efficient code which relies on objects’

layout known at compile-time. Thus type-safety violations are prevented by the compiler generating compile-time errors.

 1 class Base {
 2    foo (p: Base) {}
 3 }
 4 class Derived extends Base {
 5    override foo (p: Derived)
 6       // |LANG| will issue a compile-time error - incorrect overriding
 7    {
 8        console.log ("p.field unassigned = ", p.field)
 9           // |TS| will print 'p.field unassigned =  undefined'
10        p.field = 666 // Access the field
11        console.log ("p.field assigned   = ", p.field)
12           // |TS| will print 'p.field assigned   =  666'
13        p.method() // Call the method
14           // |TS| will generate runtime error: TypeError: p.method is not a function
15    }
16    method () {}
17    field: number = 0
18 }
19
20 let base: Base = new Derived
21 base.foo (new Base)

21.4. Differences in Math.pow

The function Math.pow in ArkTS conforms to the latest IEEE 754-2019 standard, and the following calls:

  • Math.pow(1, Infinity)

  • Math.pow(-1, Infinity)

  • Math.pow(1, -Infinity)

  • Math.pow(-1, -Infinity)

—produce the result 1 (one).

The function Math.pow in TypeScript conforms to the outdated 2008 version of the standard, and the same calls produce NaN.