1# Only ``as T`` syntax is supported for type casts 2 3Rule ``arkts-as-casts`` 4 5**Severity: error** 6 7ArkTS supports the keyword ``as`` as the only syntax for type casts. 8Incorrect cast causes a compile-time error or runtime ``ClassCastException``. 9``<type>`` syntax for type casts is not supported. 10 11Use the expression ``new ...`` instead of ``as`` if a **primitive** type 12(e.g., a ``number`` or a ``boolean``) must be cast to the reference type. 13 14 15## TypeScript 16 17 18``` 19 20 class Shape {} 21 class Circle extends Shape {x: number = 5} 22 class Square extends Shape {y: string = "a"} 23 24 function createShape(): Shape { 25 return new Circle() 26 } 27 28 let c1 = <Circle> createShape() 29 30 let c2 = createShape() as Circle 31 32 // No report is provided during compilation 33 // nor during runtime if cast is wrong: 34 let c3 = createShape() as Square 35 console.log(c3.y) // undefined 36 37 // Important corner case for casting primitives to the boxed counterparts: 38 // The left operand is not properly boxed here in in runtime 39 // because "as" has no runtime effect in TypeScript 40 let e1 = (5.0 as Number) instanceof Number // false 41 42 // Number object is created and instanceof works as expected: 43 let e2 = (new Number(5.0)) instanceof Number // true 44 45``` 46 47## ArkTS 48 49 50``` 51 52 class Shape {} 53 class Circle extends Shape {x: number = 5} 54 class Square extends Shape {y: string = "a"} 55 56 function createShape(): Shape { 57 return new Circle() 58 } 59 60 let c2 = createShape() as Circle 61 62 // ClassCastException during runtime is thrown: 63 let c3 = createShape() as Square 64 65 // Number object is created and instanceof works as expected: 66 let e2 = (new Number(5.0)) instanceof Number // true 67 68``` 69 70 71