1.. 2 Copyright (c) 2021-2025 Huawei Device Co., Ltd. 3 Licensed under the Apache License, Version 2.0 (the "License"); 4 you may not use this file except in compliance with the License. 5 You may obtain a copy of the License at 6 http://www.apache.org/licenses/LICENSE-2.0 7 Unless required by applicable law or agreed to in writing, software 8 distributed under the License is distributed on an "AS IS" BASIS, 9 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 See the License for the specific language governing permissions and 11 limitations under the License. 12 13.. _Expressions: 14 15Expressions 16########### 17 18.. meta: 19 frontend_status: Partly 20 21This chapter describes the meanings of expressions and the rules for the 22evaluation of expressions, except the expressions related to coroutines 23(see :ref:`Coroutines (Experimental)`) and expressions described as experimental 24(see :ref:`Lambda Expressions with Receiver`). 25 26.. index:: 27 evaluation 28 expression 29 coroutine 30 31The syntax of *expression* is presented below: 32 33.. code-block:: abnf 34 35 expression: 36 primaryExpression 37 | instanceOfExpression 38 | castExpression 39 | typeOfExpression 40 | nullishCoalescingExpression 41 | spreadExpression 42 | unaryExpression 43 | binaryExpression 44 | assignmentExpression 45 | conditionalExpression 46 | stringInterpolation 47 | lambdaExpression 48 | lambdaExpressionWithReceiver 49 | awaitExpression 50 ; 51 primaryExpression: 52 literal 53 | namedReference 54 | arrayLiteral 55 | objectLiteral 56 | recordLiteral 57 | thisExpression 58 | parenthesizedExpression 59 | methodCallExpression 60 | fieldAccessExpression 61 | indexingExpression 62 | functionCallExpression 63 | newExpression 64 | ensureNotNullishExpression 65 ; 66 binaryExpression: 67 multiplicativeExpression 68 | additiveExpression 69 | shiftExpression 70 | relationalExpression 71 | equalityExpression 72 | bitwiseAndLogicalExpression 73 | conditionalAndExpression 74 | conditionalOrExpression 75 ; 76 77The syntax below introduce several productions to be used by other 78expression syntax rules: 79 80.. code-block:: abnf 81 82 objectReference: 83 typeReference 84 | 'super' 85 | primaryExpression 86 ; 87 88``objectReference`` refers to one of the following three options: 89 90- Class that is to handle static members; 91- ``super`` that is to access constructors declared in the 92 superclass, or the overridden method version of the superclass; 93- *primaryExpression* that is to refer to an instance variable of a class, 94 interface, or function type after evaluation, unless the manner of the 95 evaluation is altered by the chaining operator '``?.``' (see 96 :ref:`Chaining Operator`). 97 98If the form of *primaryExpression* is *thisExpression*, then the pattern 99"``this?.``" is handled as a :index:`compile-time error`. 100 101If the form of *primaryExpression* is *super*, then the pattern "``super?.``" 102is handled as a :index:`compile-time error`. 103 104.. index:: 105 field 106 constructor 107 superclass 108 overriding 109 method 110 variable 111 expression 112 instance variable 113 class 114 interface 115 function type 116 evaluation 117 chaining operator 118 pattern 119 120The syntax of *arguments* is presented below: 121 122.. code-block:: abnf 123 124 arguments: 125 '(' argumentSequence? ')' 126 ; 127 128 argumentSequence: 129 restArgument 130 | expression (',' expression)* (',' restArgument)? ','? 131 ; 132 133 restArgument: 134 '...'? expression 135 ; 136 137The *arguments* grammar rule refers to the list of arguments of a call. Only 138the last argument can have the form of a spread expression (see 139:ref:`Spread Expression`). 140 141.. index:: 142 argument 143 grammar rule 144 spread expression 145 146| 147 148.. _Evaluation of Expressions: 149 150Evaluation of Expressions 151************************* 152 153.. meta: 154 frontend_status: Done 155 todo: needs more investigation, too much failing CTS tests (mostly tests are buggy) 156 157The result of a program expression *evaluation* denotes the following: 158 159- Variable (the term *variable* is used here in the general, non-terminological 160 sense to denote a modifiable lvalue in the left-hand side of an assignment); 161 or 162- Value (results found elsewhere). 163 164.. index:: 165 evaluation 166 expression 167 variable 168 lvalue 169 assignment 170 171A variable or a value are equally considered the *value of the expression* 172if such a value is required for further evaluation. 173 174The type of an expression is evaluated at compile time (see 175:ref:`Type of Expression`). 176 177Expressions can contain assignments, increment operators, decrement operators, 178method calls, and function calls. The evaluation of an expression can produce 179side effects as a result. 180 181*Constant expressions* (see :ref:`Constant Expressions`) are the expressions 182with values that can be determined at compile time. 183 184.. index:: 185 variable 186 value 187 evaluation 188 expression 189 type 190 assignment 191 increment operator 192 decrement operator 193 method call 194 function call 195 side effect 196 constant expression 197 compile time 198 199| 200 201.. _Normal and Abrupt Completion of Expression Evaluation: 202 203Normal and Abrupt Completion of Expression Evaluation 204===================================================== 205 206.. meta: 207 frontend_status: Done 208 209Each expression in a normal mode of evaluation requires certain computational 210steps. Normal modes of evaluation for each kind of expression are described 211in the following sections. 212 213An expression evaluation *completes normally* if all computational steps 214are performed without throwing an error. 215 216On the contrary, an expression *completes abruptly* if the expression 217evaluation throws an error. 218 219The information about the causes of an abrupt completion can be available 220in the value attached to the error object. 221 222.. index:: 223 normal completion 224 abrupt completion 225 evaluation 226 expression 227 value 228 229Runtime errors can occur as a result of expression or operator evaluation as 230follows: 231 232- If an *array reference expression* has the value ``null``, then an *array 233 indexing expression* (see :ref:`Array Indexing Expression`) throws 234 ``NullPointerError``. 235- If the value of an array index expression is negative, or greater than, or 236 equal to the length of the array, then an *array indexing expression* (see 237 :ref:`Array Indexing Expression`) throws ``ArrayIndexOutOfBoundsError``. 238- If a conversion cannot be performed at runtime, then a 239 :ref:`Cast Expression` throws ``ClassCastError``. 240- If the right-hand expression has the zero value, then integer 241 division (see :ref:`Division`), or integer remainder (see :ref:`Remainder`) 242 operators throw ``ArithmeticError``. 243 244.. index:: 245 predefined operator 246 runtime error 247 array reference expression 248 value 249 array access expression 250 error 251 array indexing expression 252 array 253 runtime 254 cast expression 255 integer division 256 integer remainder 257 operator 258 remainder operator 259 array element 260 reference type 261 array literal 262 method call expression 263 prefix 264 postfix 265 increment operator 266 decrement operator 267 array element type 268 cast 269 assignment 270 271Possible hard-to-predict and hard-to-handle linkage and virtual machine errors 272can cause errors during the evaluation of an expression. 273 274Abrupt completion of the evaluation of a subexpression results in the following: 275 276- Immediate abrupt completion of the expression that contains such a 277 subexpression (if the evaluation of the contained subexpression is required 278 for the evaluation of the entire expression); and 279- Cancellation of all subsequent steps of the normal mode of evaluation. 280 281The terms *complete normally* and *complete abruptly* can also denote 282normal and abrupt completion of the execution of statements (see 283:ref:`Normal and Abrupt Statement Execution`). A statement can complete 284abruptly for a variety of reasons in addition to an error being thrown. 285 286.. index:: 287 normal completion 288 abrupt completion 289 execution 290 statement 291 virtual machine 292 expression 293 subexpression 294 evaluation 295 linkage 296 297| 298 299.. _Order of Expression Evaluation: 300 301Order of Expression Evaluation 302============================== 303 304.. meta: 305 frontend_status: Done 306 307The operands of an operator are evaluated from left to right in accordance with 308the following rules: 309 310- for order of evaluation assignment operator see :ref:`Assignment`. 311 312- Any right-hand expression is evaluated only after the left-hand expression of a 313 binary operator is fully evaluated. 314 315- Any part of the operation can be executed only after every operand of an 316 operator (except conditional operators '``&&``', '``||``', and '``?:``') 317 is fully evaluated. 318 319 The execution of a binary operator that is an integer division '``/``' (see 320 :ref:`Division`), or integer remainder '``%``' (see :ref:`Remainder`) can 321 throw ``ArithmeticError`` only after the evaluations of both operands 322 complete normally. 323- The |LANG| programming language follows the order of evaluation as indicated 324 explicitly by parentheses, and implicitly by the precedence of operators. 325 This rule particularly applies for infinity and ``NaN`` values of floating-point 326 calculations. 327 |LANG| considers integer addition and multiplication as provably associative; 328 however, floating-point calculations must not be naively reordered because 329 they are unlikely to be computationally associative (even though they appear 330 mathematically associative). 331 332.. index:: 333 operand 334 abrupt completion 335 evaluation 336 operator 337 conditional operator 338 integer division 339 integer remainder 340 expression 341 binary operator 342 compound-assignment operator 343 simple assignment operator 344 variable 345 value 346 operator 347 error 348 precedence 349 operator precedence 350 infinity 351 NaN value 352 floating-point calculation 353 integer addition 354 integer multiplication 355 associativity 356 parenthesis 357 358| 359 360.. _Operator Precedence: 361 362Operator Precedence 363=================== 364 365.. meta: 366 frontend_status: Partly 367 todo: fix 'await' precedence 368 369The table below summarizes all information on the precedence and 370associativity of operators. Each section on a particular operator 371also contains detailed information. 372 373.. index:: 374 precedence 375 operator precedence 376 operator 377 associativity 378 379 380.. list-table:: 381 :width: 100% 382 :widths: 35 50 15 383 :header-rows: 1 384 385 * - Operator 386 - Precedence 387 - Associativity 388 * - grouping 389 - ``()`` 390 - n/a 391 * - member access and chaining 392 - ``.`` ``?.`` 393 - left-to-right 394 * - access and call 395 - ``[]`` ``.`` ``()`` ``new`` 396 - n/a 397 * - postfix increment and decrement 398 - ``++`` ``--`` 399 - n/a 400 * - prefix increment and decrement, unary operators, typeof, await 401 - ``++ -- + - ! ~ typeof await`` 402 - n/a 403 * - exponentiation 404 - ``**`` 405 - right-to-left 406 * - multiplicative 407 - ``* / %`` 408 - left-to-right 409 * - additive 410 - ``+ -`` 411 - left-to-right 412 * - cast 413 - ``as`` 414 - left-to-right 415 * - shift 416 - ``<< >> >>>`` 417 - left-to-right 418 * - relational 419 - ``< > <= >= instanceof`` 420 - left-to-right 421 * - equality 422 - ``== !=`` 423 - left-to-right 424 * - bitwise AND 425 - ``&`` 426 - left-to-right 427 * - bitwise exclusive OR 428 - ``^`` 429 - left-to-right 430 * - bitwise inclusive OR 431 - ``|`` 432 - left-to-right 433 * - logical AND 434 - ``&&`` 435 - left-to-right 436 * - logical OR 437 - ``||`` 438 - left-to-right 439 * - null-coalescing 440 - ``??`` 441 - left-to-right 442 * - ternary 443 - ``?:`` 444 - right-to-left 445 * - assignment 446 - ``= += -= %= *= /= &= ^= |= <<= >>= >>>=`` 447 - right-to-left 448 449 450 451.. index:: 452 precedence 453 bitwise operator 454 null-coalescing operator 455 assignment 456 shift operator 457 cast operator 458 equality operator 459 postfix operator 460 increment operator 461 decrement operator 462 prefix operator 463 logical operator 464 relational operator 465 466| 467 468.. _Evaluation of Arguments: 469 470Evaluation of Arguments 471======================= 472 473.. meta: 474 frontend_status: Done 475 476An evaluation of arguments always progresses from left to right up to the first 477error, or through the end of the expression; i.e., any argument expression is 478evaluated after the evaluation of each argument expression to its left 479completes normally (including comma-separated argument expressions that appear 480within parentheses in method calls, constructor calls, class instance creation 481expressions, or function call expressions). 482 483If the left-hand argument expression completes abruptly, then no part of the 484right-hand argument expression is evaluated. 485 486.. index:: 487 evaluation 488 argument 489 error 490 expression 491 normal completion 492 comma-separated argument expression 493 method call 494 constructor call 495 class instance creation expression 496 instance 497 function call expression 498 abrupt completion 499 500| 501 502.. _Evaluation of Other Expressions: 503 504Evaluation of Other Expressions 505=============================== 506 507.. meta: 508 frontend_status: Done 509 510These general rules cannot cover the order of evaluation of certain expressions 511when they from time to time cause exceptional conditions. The order of 512evaluation of the following expressions requires specific explanation: 513 514- Class instance creation expressions (see :ref:`New Expressions`); 515- :ref:`Resizable Array Creation Expressions`; 516- :ref:`Indexing Expressions`; 517- Method call expressions (see :ref:`Method Call Expression`); 518- Assignments involving indexing (see :ref:`Assignment`); 519- :ref:`Lambda Expressions`. 520 521.. index:: 522 evaluation 523 expression 524 method call expression 525 class instance creation expression 526 array creation expression 527 indexing expression 528 assignment 529 indexing 530 lambda 531 lambda expression 532 533| 534 535.. _Literal: 536 537Literal 538******* 539 540.. meta: 541 frontend_status: Done 542 543Literals (see :ref:`Literals`) denote fixed and unchanging values. Type of 544a literal (see :ref:`Literals`) is the type of an expression. 545 546.. index:: 547 literal 548 value 549 550| 551 552.. _Named Reference: 553 554Named Reference 555*************** 556 557.. meta: 558 frontend_status: Done 559 560An expression can have the form of a *named reference* as described by the 561syntax rule as follows: 562 563.. code-block:: abnf 564 565 namedReference: 566 qualifiedName typeArguments? 567 ; 568 569Type of a *named reference* expression is the type of the entity a 570*named reference* refers to. 571 572*QualifiedName* (see :ref:`Names`) is an expression that consists of 573dot-separated names. If *qualifiedName* consists of a single identifier, then 574it is called a *simple name*. 575 576.. index:: 577 expression 578 named reference 579 syntax 580 entity 581 dot-separated name 582 simple name 583 584*Simple name* refers to the following: 585 586- Entity declared in the current compilation unit; 587- Local variable or parameter of the surrounding function or method. 588 589If not a *simple name*, *qualifiedName* refers to the following: 590 591- Entity imported from a compilation unit, 592- Entity exported from a namespace, or 593- Member of some class or interface, or 594- Special syntax form of :ref:`Record Indexing Expression`. 595 596If *typeArguments* are provided, then *qualifiedName* is a valid instantiation 597of the generic method or function. Otherwise, a :index:`compile-time error` 598occurs. 599 600A :index:`compile-time error` also occurs in the following situations: 601 602- If a name referred by *qualifiedName* is undefined or inaccessible; or 603- If ambiguity occurs while resolving a name except the function or method 604 overloading case (see :ref:`Function, Method and Constructor Overloading`). 605 606Type of a *named reference* is the type of an expression. 607 608If a *named reference* refers to a non-static method of a class or an interface 609then the named reference is bounded with the object of that class or interface. 610 611.. index:: 612 simple name 613 entity 614 compilation unit 615 compile-time error 616 namespace 617 named reference 618 expression 619 overloading 620 generic method 621 ambiguity 622 623.. code-block:: typescript 624 :linenos: 625 626 import * as compilationUnitName from "someFile" 627 628 class Type { 629 static method() {} 630 method () { 631 let local = this.method // Qualified name referring an instance method 632 } 633 } 634 const m1 = Type.method // Qualified name referring a static method 635 const m2 = (new Type).method 636 637 function foo (parameter: Type) { 638 let local: Type = parameter /* 'parameter' here is the 639 expression in the form of simple name, type of 'parameter' is the 640 explicitly declared function parameter type */ 641 local = new Type () /* 'local' here is the expression in the 642 form of simple name */ 643 local = compilationUnitName.someExportedVariable /* qualifiedName here 644 refers to a variable imported from a compilation unit */ 645 let func = foo /* foo is a simple name of the function declared in this 646 module, type of 'func' is the function type derived from the function 647 'foo()' signature. func itself is a new function object */ 648 649 goo() // goo is an undefined name - compile-time error 650 let bar_ref = bar // bar is an ambiguous reference - compile-time error 651 } 652 653 function bar (p: string) {} 654 function bar (p: number) {} 655 656 function generic_function<T> () {} 657 let instantiation = generic_function<string> /* type of 'instantiation' is 658 a function type derived from the signature of instantiated function 659 'generic_function<string> ()' */ 660 661 662 class aClass { 663 field = 123 664 method(): number { return this.field } 665 } 666 const anObject = new aClass 667 const aMethod = anObject.method 668 anObject.field = 42 669 console.log (aMethod()) // Outputs 42 670 671 let global: Object = goo() 672 function goo() { 673 console.log (global) // compile-time or runtime error 674 } 675 676 677| 678 679.. _Array Literal: 680 681Array Literal 682************* 683 684.. meta: 685 frontend_status: Done 686 todo: let x : int = [1,2,3][1] - valid? 687 todo: let x = ([1,2,3][1]) - should be CTE, but it isn't 688 todo: implement it properly for invocation context to get type from the context, not from the first element 689 690*Array literal* is an expression that can be used to create an array or 691tuple in some cases, and to provide some initial values. 692 693The syntax of *array literal* is presented below: 694 695.. code-block:: abnf 696 697 arrayLiteral: 698 '[' expressionSequence? ']' 699 ; 700 701 expressionSequence: 702 expression (',' expression)* ','? 703 ; 704 705An *array literal* is a comma-separated list of *initializer expressions* 706enclosed in '``[``' and '``]``'. A trailing comma after the last 707expression in an array literal is ignored: 708 709.. index:: 710 array literal 711 array 712 tuple 713 expression 714 value 715 initializer expression 716 trailing comma 717 718.. code-block:: typescript 719 :linenos: 720 721 let x = [1, 2, 3] // ok 722 let y = [1, 2, 3,] // ok, trailing comma is ignored 723 724The number of initializer expressions enclosed in braces of the array 725initializer determines the length of the array to be constructed. 726 727If sufficient space is allocated for a new array, then a one-dimensional 728array of the specified length is created. All elements of the array 729are initialized to the values specified by initializer expressions. 730 731.. index:: 732 initializer expression 733 brace 734 length of array 735 array initializer 736 array 737 one-dimensional array 738 array element 739 initialization 740 initializer expression 741 value 742 743On the contrary, the evaluation of the array initializer completes abruptly 744in the following situations: 745 746- If the space allocated for a new array is insufficient, and 747 ``OutOfMemoryError`` is thrown; or 748- If some initialization expression completes abruptly. 749 750.. index:: 751 evaluation 752 array initializer 753 abrupt completion 754 array 755 initialization expression 756 757Initializer expressions are executed from left to right. The *n*’th expression 758specifies the value of the *n-1*’th element of the array. 759 760Array literals can be nested (i.e., the initializer expression that specifies 761an array element can be an array literal if that element is of array type). 762 763Type of an *array literal expression* is inferred by the following rules: 764 765.. index:: 766 initializer expression 767 execution 768 value 769 array element 770 array literal expression 771 array type 772 type inference 773 774- If a context is available, then type is inferred from the context. If 775 successful, then type of an array literal is the inferred type ``T[]``, 776 ``Array<T>``, or tuple. 777- Otherwise, type is to be inferred from the types of array literal 778 elements. 779 780More details of both cases are presented below. 781 782.. index:: 783 type inference 784 context 785 array literal 786 array element 787 788| 789 790.. _Array Literal Type Inference from Context: 791 792Array Literal Type Inference from Context 793========================================= 794 795.. meta: 796 frontend_status: Done 797 798Type of an array literal can be inferred from the *context*, including 799explicit type annotation of a variable declaration, left-hand part type 800of an assignment, call parameter type, or type of a cast expression: 801 802.. code-block:: typescript 803 :linenos: 804 805 let a: number[] = [1, 2, 3] // ok, variable type is used 806 a = [4, 5] // ok, variable type is used 807 808 function min(x: number[]): number { 809 let m = x[0] 810 for (let v of x) 811 if (v < m) 812 m = v 813 return m 814 } 815 min([1., 3.14, 0.99]); // ok, parameter type is used 816 817 // Two-dimensional array initialization 818 type Matrix = number[][] 819 let m: Matrix = [[1, 2], [3, 4], [5, 6]] 820 821 class aClass {} 822 let b1: Array <aClass> = [new aClass, new aClass] 823 let b2: Array <number> = [1, 2, 3] 824 let b3: FixedArray<number> = [1, 2] 825 /* Type of literal is inferred from the context 826 taken from b1, b2 and b3 declarations */ 827 828 829.. index:: 830 literal 831 string literal 832 instance 833 error 834 assignability 835 inheritance 836 context 837 array 838 tuple 839 840The following example illustrates possible kinds of context: 841 842.. code-block:: typescript 843 :linenos: 844 845 let array: number[] = [1, 2, 3] // assignment context 846 function foo (array: number[]) {} 847 foo ([1, 2, 3]) // call context 848 [1, 2, 3] as number[] // casting conversion 849 850.. index:: 851 type inference 852 context 853 array type 854 array literal 855 type 856 type annotation 857 variable declaration 858 assignment 859 call parameter type 860 cast expression 861 862All valid conversions are applied to the initializer expression, i.e., each 863initializer expression type must be assignable (see :ref:`Assignability`) 864to the array element type. Otherwise, a :index:`compile-time error` occurs. 865 866.. index:: 867 conversion 868 initializer expression 869 assignability 870 array element type 871 872.. code-block:: typescript 873 :linenos: 874 875 let value: number = 2 876 let list: Object[] = [1, value, "hello", new Error()] // ok 877 878If the type used in the context is a *tuple type* (see :ref:`Tuple Types`), 879and types of all literal expressions are compatible with tuple type elements 880at respective positions, then an array literal is of tuple type. 881 882.. code-block:: typescript 883 :linenos: 884 885 let tuple: [number, string] = [1, "hello"] // ok 886 887 let incorrect: [number, string] = ["hello", 1] // compile-time error 888 889If the type used in the context is a *union type* (see :ref:`Union Types`), then 890it is necessary to try inferring the type of the array literal from its elements 891(see :ref:`Array Type Inference from Types of Elements`). If successful, then 892the type so inferred must be compatible with one of the types that form the 893union type. Otherwise, a :index:`compile-time error` occurs: 894 895.. code-block:: typescript 896 :linenos: 897 898 let union_of_arrays: number[] | string[] = [1, 2] // OK, type of literal is number[] 899 let incorrect_union_of_arrays: number[] | string[] = [1, 2, "string"] 900 /* compile-time error: (number|string)[] (type of the literal) is not compatible with 901 number[] | string[] (type of the variable) 902 */ 903 904.. index:: 905 tuple type 906 literal expression 907 compatibility 908 context 909 literal 910 expression 911 type 912 array literal 913 union type 914 type inference 915 916If the type used in the context is a *fixed-size array type* (see 917:ref:`Fixed-size Array Types`), and each initializer expression type is 918compatible with the array element type, then an array literal is of 919*fixed-size array type*. 920 921.. code-block:: typescript 922 :linenos: 923 924 let array: FixedArray<number> = [1, 2] 925 926.. index:: 927 fixed-size array type 928 initializer expression 929 array element 930 array literal 931 932| 933 934.. _Array Type Inference from Types of Elements: 935 936Array Type Inference from Types of Elements 937=========================================== 938 939.. meta: 940 frontend_status: Done 941 942When type of an array literal ``[`` ``expr``:sub:`1`, ``...`` , ``expr``:sub:`N` ``]`` 943cannot be inferred from the context, then the following algorithm is 944used to infer it from initialization expressions: 945 946.. #. If there is no expression (*N == 0*), then type is ``Object[]``. 947 948#. If there are no elements in the array literal (*N == 0*), then type of 949 the array literal cannot be inferred, and a :index:`compile-time error` 950 occurs. 951 952#. If type of at least one of element expression cannot be determined, then 953 type of the array literal cannot be inferred, and a 954 :index:`compile-time error` occurs. 955 956#. If each initialization expression is of numeric type (see 957 :ref:`Numeric Types`), then the type of the array literal is ``number[]``. 958 959#. If all initialization expressions are of the same type ``T``, then the 960 type of the array literal is ``T[]``. 961 962#. Otherwise, the type of array literal is constructed as the union type 963 ``T``:sub:1 ``| ... | T``:sub:N, 964 where ``T``:sub:i is the type of *expr*:sub:i and then: 965 966 - If ``T``:sub:i is a literal type, then it is replaced for its supertype; 967 968 - If ``T``:sub:i is a union type that contains literal types, 969 then each literal type is replaced for its supertype. 970 971 - :ref:`Union Types Normalization` is applied 972 to the resultant union type after these replacements. 973 974.. index:: 975 type inference 976 array element 977 array literal 978 type 979 context 980 initialization expression 981 expression 982 numeric type 983 union type normalization 984 union type 985 986.. code-block:: typescript 987 :linenos: 988 989 let u : "A" | "B" = "A" 990 991 let a = [] // compile-time error, type cannot be inferred 992 let b = ["a"] // type is string[] 993 let c = [1, 2, 3] // type is number[] 994 let d = ["a" + "b", 1, 3.14] // type is (string | number)[] 995 let e = [u] // type is string[] 996 let f = [(): void => {}, new A()] // type is (() => void | A)[] 997 998| 999 1000.. _Object Literal: 1001 1002Object Literal 1003*************** 1004 1005.. meta: 1006 frontend_status: Done 1007 1008*Object literal* is an expression that can be used to create a class instance 1009with methods and fields with initial values. In some cases it is more 1010convenient to use an *object literal* in place of a class instance creation 1011expression (see :ref:`New Expressions`). 1012 1013.. index:: 1014 object literal 1015 expression 1016 instance 1017 class instance 1018 creation expression 1019 1020The syntax of *object literal* is presented below: 1021 1022.. code-block:: abnf 1023 1024 objectLiteral: 1025 '{' objectLiteralMembers? '}' 1026 ; 1027 1028 objectLiteralMembers: 1029 objectLiteralMember (',' objectLiteralMember)* ','? 1030 ; 1031 1032 objectLiteralMember: 1033 objectLiteralField | objectLiteralMethod 1034 ; 1035 1036 objectLiteralField: 1037 identifier ':' expression 1038 ; 1039 1040 objectLiteralMethod 1041 identifier typeParameters? signature block 1042 ; 1043 1044 1045An *object literal* is written as a comma-separated list of 1046*object literal members* enclosed in curly braces '``{``' and '``}``'. A 1047trailing comma after the last member is ignored. Each *object literal member* 1048can be either an *object literal field* or an *object literal method*. 1049 1050**Note**. All methods of an *object literal* are public. 1051 1052An *object literal field* consists of an identifier and an expression as follows: 1053 1054.. index:: 1055 object literal 1056 comma-separated list 1057 name-value pair 1058 curly brace 1059 trailing comma 1060 identifier 1061 expression 1062 1063.. code-block:: typescript 1064 :linenos: 1065 1066 class Person { 1067 name: string = "" 1068 age: number = 0 1069 } 1070 let b: Person = {name: "Bob", age: 25} 1071 let a: Person = {name: "Alice", age: 18, } //ok, trailing comma is ignored 1072 let c: Person | number = {name: "Mary", age: 17} // literal will be of type Person 1073 1074And *object literal method* is a complete declaration of a public method: 1075 1076.. code-block:: typescript 1077 :linenos: 1078 1079 abstract class Person { 1080 name: string = "" 1081 abstract set_name (name: string): void 1082 } 1083 let p: Person = { 1084 name: "Bob", 1085 set_name (name: string) { this.name = name } 1086 } 1087 p.set_name ("Alice") 1088 1089 1090A :index:`compile-time error` occurs if an object literal introduces new 1091methods: 1092 1093.. code-block:: typescript 1094 :linenos: 1095 1096 class Base1 {} 1097 interface Base2 {} 1098 const o1: Base1 = { m() {} } // compile-time error 1099 const o2: Base2 = { m() {} } // compile-time error 1100 1101A :index:`compile-time error` occurs if a class has a private or a protected 1102method, and its object literal contains same-name methods with 1103override-compatible signatures (see :ref:`Override-Compatible Signatures`): 1104 1105.. code-block:: typescript 1106 :linenos: 1107 1108 class Base {} 1109 class Derived extends Base {} 1110 class aClass { 1111 private method (p: Derived): Base { return new Base } 1112 } 1113 const x: aClass = { 1114 method (p: Base): Derived { return new Derived } // compile-time error 1115 method () {} // OK as it is not an overriding case 1116 } 1117 1118 interface I { 1119 method (p: Derived): Base 1120 } 1121 const o: I = { 1122 method (p: Base): Derived { return new Derived } // OK 1123 } 1124 o.method (new Derived) // OK 1125 o.method (new Base) // compile-time error 1126 1127If a class or an interface has some method implementaion, then its object 1128literal can skip providing a new implemention of this method: 1129 1130.. code-block:: typescript 1131 :linenos: 1132 1133 class Base { 1134 method () { console.log ("method() from Base is called") } 1135 } 1136 const x: Base = {} // Valid literal of type Base 1137 x.method () 1138 1139 interface I { 1140 method () { console.log ("method() from I is called") } 1141 } 1142 const x: I = {} // Valid literal of anonymous class type 1143 x.method () 1144 1145 1146 1147Type of an *object literal expression* is always some class ``C`` that is 1148inferred from the context. A type inferred from the context can be either a 1149named class (see :ref:`Object Literal of Class Type`), or an anonymous class 1150created for the inferred interface type (see 1151:ref:`Object Literal of Interface Type`). 1152 1153A :index:`compile-time error` occurs if: 1154 1155- Type of an object literal cannot be inferred from the context; 1156- The inferred type is not a class or interface type; 1157- The context is a union type, and an object literal can be treated 1158 as value of several of union component types; or 1159- The inferred type has abstract methods (see :ref:`Abstract Methods`). 1160 1161 **Note**. An abstract class without abstract methods can be used. 1162 1163.. index:: 1164 object literal expression 1165 type inference 1166 named class 1167 abstract method 1168 abstract class 1169 anonymous class 1170 context 1171 class type 1172 anonymous class 1173 interface type 1174 compile-time error 1175 inferred type 1176 1177.. code-block:: typescript 1178 :linenos: 1179 1180 let p = {name: "Bob", age: 25} 1181 // compile-time error, type cannot be inferred 1182 1183 class A { field = 1 } 1184 class B { field = 2 } 1185 1186 let q: A | B = {field: 6} 1187 // compile-time error, type cannot be inferred as the literal 1188 // fits both A and B 1189 1190 1191| 1192 1193.. _Object Literal of Class Type: 1194 1195Object Literal of Class Type 1196============================= 1197 1198.. meta: 1199 frontend_status: Done 1200 1201If class type ``C`` is inferred from the context, then type of an object 1202literal is ``C``: 1203 1204.. index:: 1205 object literal 1206 class type 1207 type inference 1208 context 1209 1210.. code-block:: typescript 1211 :linenos: 1212 1213 class Person { 1214 name: string = "" 1215 age: number = 0 1216 } 1217 function foo(p: Person) { /*some code*/ } 1218 // ... 1219 let p: Person = {name: "Bob", age: 25} /* ok, variable type is 1220 used */ 1221 foo({name: "Alice", age: 18}) // ok, parameter type is used 1222 1223An identifier in each *name-value pair* must name a field of class ``C``, 1224or a field of any superclass of class ``C``. 1225 1226A :index:`compile-time error` occurs if the identifier does not name an 1227*accessible member field* (see :ref:`Accessible`) in type ``C``: 1228 1229.. index:: 1230 identifier 1231 name-value pair 1232 field 1233 superclass 1234 class 1235 compile-time error 1236 accessible member field 1237 1238.. code-block:: typescript 1239 :linenos: 1240 1241 class Friend { 1242 name: string = "" 1243 private nick: string = "" 1244 age: number 1245 sex?: "male"|"female" 1246 } 1247 // compile-time error, nick is private: 1248 let f: Friend = {name: "Alexander", age: 55, nick: "Alex"} 1249 1250A :index:`compile-time error` occurs if type of an expression in a 1251*name-value pair* is not assignable (see :ref:`Assignability`) to the 1252field type: 1253 1254.. code-block:: typescript 1255 :linenos: 1256 1257 let f: Friend = {name: 123} /* compile-time error - type of right hand-side 1258 is not assignable to the type of the left hand-side */ 1259 1260If some class fields have default values (see :ref:`Default Values for Types`) 1261or explicit initializers (see :ref:`Variable and Constant Declarations`), then 1262such fields can be skipped in the object literal. 1263 1264.. index:: 1265 expression 1266 name-value pair 1267 compatibility 1268 field type 1269 class field 1270 object literal 1271 initializer 1272 1273.. code-block:: typescript 1274 :linenos: 1275 1276 let f: Friend = {} /* OK, as name, nick, age, and sex have either default 1277 value or explicit initializer */ 1278 1279If an object literal is to use class ``C``, then class ``C`` must have a 1280*parameterless* constructor (explicit or default) that is *accessible* 1281(see :ref:`Accessible`) in the class-composite context. 1282 1283A :index:`compile-time error` occurs if: 1284 1285- ``C`` contains no parameterless constructor; or 1286- No constructor is accessible (see :ref:`Accessible`). 1287 1288These situations are presented in the examples below: 1289 1290.. index:: 1291 parameterless constructor 1292 accessibility 1293 context 1294 object literal 1295 1296.. code-block:: typescript 1297 :linenos: 1298 1299 class C { 1300 constructor (x: number) {} 1301 } 1302 // ... 1303 let c: C = {} /* compile-time error - no parameterless 1304 constructor */ 1305 1306.. code-block:: typescript 1307 :linenos: 1308 1309 class C { 1310 private constructor () {} 1311 } 1312 // ... 1313 let c: C = {} /* compile-time error - constructor is not 1314 accessible */ 1315 1316If a class has accessors (see :ref:`Accessor Declarations`) for a property, 1317and its setter is provided, then this property can be used as a part of an 1318object literal. Otherwise, a :index:`compile-time error` occurs: 1319 1320.. code-block:: typescript 1321 :linenos: 1322 1323 class OK { 1324 set attr (attr: number) {} 1325 } 1326 const a: OK = {attr: 42} // OK, as the setter be called 1327 1328 class Err { 1329 get attr (): number { return 42 } 1330 } 1331 const b: Err = {attr: 42} // compile-time error - no setter for 'attr' 1332 1333.. index:: 1334 accessor 1335 setter 1336 object literal 1337 1338| 1339 1340.. _Object Literal of Interface Type: 1341 1342Object Literal of Interface Type 1343================================ 1344 1345.. meta: 1346 frontend_status: Done 1347 1348If the interface type ``I`` is inferred from the context, then type of an 1349object literal is an anonymous class implicitly created for interface ``I``: 1350 1351.. code-block:: typescript 1352 :linenos: 1353 1354 interface Person { 1355 name: string 1356 age: number 1357 } 1358 let b: Person = {name: "Bob", age: 25} 1359 1360In the example above, type of *b* is an anonymous class that contains the 1361same fields as the interface ``I`` properties. 1362 1363.. index:: 1364 interface type 1365 type inference 1366 context 1367 object literal 1368 anonymous class 1369 interface 1370 field 1371 1372If some interface properties are of an optional type, then such properties can 1373be skipped in an object literal, their values are set to ``undefined``: 1374 1375.. code-block:: typescript 1376 :linenos: 1377 1378 interface Person { 1379 name: string 1380 age: number 1381 sex?: "male"|"female" 1382 } 1383 let b: Person = {name: "Bob", age: 25} 1384 // 'sex' field will have 'undefined' value 1385 1386Properties of a non-optional type cannot be skipped in an object literal, 1387despite some property types having default values (see 1388:ref:`Default Values for Types`). If a non-optional property (e.g., *age* in 1389the example above) is skipped, then a :index:`compile-time error` occurs. 1390 1391Interface type ``I`` must contain properties only. If interface type ``I`` 1392contains a method, then a :index:`compile-time error` occurs as follows: 1393 1394.. index:: 1395 object literal 1396 interface type 1397 interface property 1398 undefined value 1399 union type 1400 inference type 1401 interface 1402 property 1403 method 1404 1405.. code-block:: typescript 1406 :linenos: 1407 1408 interface I { 1409 name: string 1410 foo() 1411 } 1412 let i : I = {name: "Bob"} // compile-time error, interface has methods 1413 1414If an interface has accessors (see :ref:`Accessor Declarations`) for some 1415property, and the property is used in an object literal, then a 1416:index:`compile-time error` occurs: 1417 1418.. code-block:: typescript 1419 :linenos: 1420 1421 interface I1 { 1422 set attr (attr: number) 1423 } 1424 const a: I1 = {attr: 42} /* compile-time error - 'attr' cannot be used 1425 in object literal */ 1426 1427 interface I2 { 1428 get attr (): number 1429 } 1430 const b: I2 = {attr: 42} /* compile-time error - 'attr' cannot be used 1431 in object literal */ 1432 1433.. index:: 1434 interface 1435 accessor 1436 property 1437 object literal 1438 1439| 1440 1441.. _Object Literal of Record Type: 1442 1443Object Literal of ``Record`` Type 1444================================= 1445 1446.. meta: 1447 frontend_status: Done 1448 1449Generic type ``Record<Key, Value>`` (see :ref:`Record Utility Type`) is used 1450to map properties of a type (type ``Key``) to another type (type ``Value``). 1451A special form of object literal is used to initialize the value of such 1452type: 1453 1454.. index:: 1455 object literal 1456 generic type 1457 record type 1458 type property 1459 type value 1460 type key 1461 initialization 1462 value 1463 1464The syntax of *record literal* is presented below: 1465 1466.. code-block:: abnf 1467 1468 recordLiteral: 1469 '{' keyValueSequence? '}' 1470 ; 1471 1472 keyValueSequence: 1473 keyValue (',' keyValue)* ','? 1474 ; 1475 1476 keyValue: 1477 expression ':' expression 1478 ; 1479 1480The first expression in ``keyValue`` denotes a key and must be of type ``Key``. 1481The second expression denotes a value and must be of type ``Value``: 1482 1483.. index:: 1484 expression 1485 key 1486 value 1487 1488.. code-block:: typescript 1489 1490 let map: Record<string, number> = { 1491 "John": 25, 1492 "Mary": 21, 1493 } 1494 1495 console.log(map["John"]) // prints 25 1496 1497.. code-block:: typescript 1498 1499 interface PersonInfo { 1500 age: number 1501 salary: number 1502 } 1503 let map: Record<string, PersonInfo> = { 1504 "John": { age: 25, salary: 10}, 1505 "Mary": { age: 21, salary: 20} 1506 } 1507 1508If a key is a union of literal types or an enum type, then all variants 1509must be listed in the object literal. Otherwise, a :index:`compile-time error` 1510occurs: 1511 1512.. index:: 1513 key 1514 union type 1515 literal 1516 object literal 1517 1518.. code-block:: typescript 1519 1520 let map: Record<"aa" | "bb", number> = { 1521 "aa": 1, 1522 } // compile-time error: "bb" key is missing 1523 1524 enum Enum {A, B} 1525 const map1: Record<Enum, number> = { 1526 Enum.A: 1 1527 } // compile-time error: key "Enum.b" is missing 1528 1529 1530| 1531 1532.. _Object Literal Evaluation: 1533 1534Object Literal Evaluation 1535========================= 1536 1537.. meta: 1538 frontend_status: Done 1539 1540The evaluation of an object literal of type ``C`` (where ``C`` is either 1541a named class type or an anonymous class type created for the interface) 1542is to be performed by the following steps: 1543 1544- A parameterless constructor is executed to produce an instance ``x`` of 1545 class ``C``. The execution of the object literal completes abruptly 1546 if so does the execution of the constructor. 1547 1548- Name-value pairs of the object literal are then executed from left to 1549 right in the textual order they occur in the source code. The execution 1550 of a name-value pair includes the following: 1551 1552 - Evaluation of the expression; and 1553 - Assignment of the value of expression to the corresponding field of ``x`` 1554 as its initial value. This rule also applies to ``readonly`` fields. 1555 1556.. index:: 1557 object literal 1558 evaluation 1559 named class 1560 anonymous class 1561 interface 1562 parameterless constructor 1563 constructor 1564 instance 1565 execution 1566 abrupt completion 1567 name-value pair 1568 field 1569 value 1570 expression 1571 assignment 1572 literal type 1573 readonly field 1574 1575The execution of an object literal completes abruptly if so does 1576the execution of a name-value pair. 1577 1578An object literal completes normally with the value of a newly 1579initialized class instance if so do all name-value pairs. 1580 1581.. index:: 1582 execution 1583 object literal 1584 abrupt completion 1585 normal completion 1586 name-value pair 1587 evaluation 1588 initialization 1589 class instance 1590 1591| 1592 1593.. _spread Expression: 1594 1595Spread Expression 1596***************** 1597 1598.. meta: 1599 frontend_status: Done 1600 1601*Spread expression* can be used only within an array literal (see 1602:ref:`Array Literal`) or argument passing. The *expression* must be of 1603array type (see :ref:`Array Types`) or tuple type (see :ref:`Tuple Types`) or 1604any type which has iteraror defined (see :ref:`Iterable Types`). 1605Otherwise, a :index:`compile-time error` occurs. 1606 1607The syntax of *spread expression* is presented below: 1608 1609.. code-block:: abnf 1610 1611 spreadExpression: 1612 '...' expression 1613 ; 1614 1615A *spread expression* for arrays or tuples or iterable types can be evaluated 1616as follows: 1617 1618- By the compiler at compile time if *expression* is constant (see 1619 :ref:`Constant Expressions`); 1620- At runtime otherwise. 1621 1622An array or tuple or iterable object referred by the *expression* is broken by 1623the evaluation into a sequence of values. This sequence is used where a 1624*spread expression* is used. It can be an assignment, a call of a function, 1625method, or constructor. A sequence of types of these values is the type of the 1626*spread expression*. 1627 1628.. index:: 1629 spread expression 1630 array literal 1631 argument 1632 expression 1633 array type 1634 tuple type 1635 iterable type 1636 runtime 1637 compiler 1638 evaluation 1639 call 1640 function 1641 method 1642 constructor 1643 assignment 1644 1645.. code-block:: typescript 1646 :linenos: 1647 1648 let array1 = [1, 2, 3] 1649 let array2 = [4, 5] 1650 let array3 = [...array1, ...array2] // spread array1 and array2 elements 1651 // while building new array literal during compile-time 1652 console.log(array3) // prints [1, 2, 3, 4, 5] 1653 1654 foo (...array2) // spread array2 elements into arguments of the foo() call 1655 function foo (...array: number[]) { 1656 console.log (array) 1657 } 1658 1659 run_time_spread_application1 (array1, array2) // prints [1, 2, 3, 42, 4, 5] 1660 function run_time_spread_application1 (a1: number[], a2: number[]) { 1661 console.log ([...a1, 42, ...a2]) 1662 // array literal will be built at runtime 1663 } 1664 1665 let tuple1: [number, string, boolean] = [1, "2", true] 1666 let tuple2: [number, string] = [4, "5"] 1667 let tuple3: [number, string, boolean, number, string] = [...tuple1, ...tuple2] // spread tuple1 and tuple2 elements 1668 // while building new tuple object during compile-time 1669 console.log(tuple3) // prints [1, "2", true, 4, "5"] 1670 1671 bar (...tuple2) // spread tuple2 elements into arguments of the foo() call 1672 function bar (...tuple: [number, string]) { 1673 console.log (tuple) 1674 } 1675 1676 run_time_spread_application2 (tuple1, tuple2) // prints [1, "2", true, 42, 4, "5"] 1677 function run_time_spread_application2 (a1: [number, string, boolean], a2: [number, string]) { 1678 console.log ([...a1, 42, ...a2]) 1679 // such array literal will be built at runtime 1680 } 1681 1682 class A<T> implements Iterable<T|undefined> { // variables of type A can be spread 1683 $_iterator(): Iterator<T|undefined> { 1684 return new MyIteratorResult<T|undefined>(this.data) 1685 } 1686 private data: T[] 1687 constructor (...data: T[]) { this.data = data } 1688 } 1689 class MyIteratorResult <T> implements Iterator<T|undefined> { 1690 private data: T[] 1691 private index: number = 0 1692 next(): IteratorResult<T|undefined> { 1693 if (this.index >= this.data.length) { 1694 return MyIteratorResult.end_of_sequence 1695 } else { 1696 this.current_element.value = this.data[this.index++] 1697 return this.current_element 1698 } 1699 } 1700 constructor (data: T[]) { this.data = data } 1701 private static end_of_sequence: IteratorResult<undefined> = {done: true, value: undefined} 1702 private current_element: IteratorResult<T|undefined> = {done: false, value: undefined} 1703 } 1704 function display<T> (...p: T[]) { console.log (p) } 1705 display (... new A<number> (1, 2, 3)) // Spread A with numbers 1706 display (... new A<string> ("aaa", "bbb")) // Spread A with strings 1707 display (... new A<Object> (1, "aaa", true)) // Spread A with any objects 1708 display (... new A<undefined>) // Spread A with no objects 1709 1710 1711**Note**. If an argument is spread at the call site, then an appropriate 1712parameter must be of the rest kind (see :ref:`Rest Parameter`). If an argument 1713is spread into a sequence of ordinary non-optional parameters, then a 1714:index:`compile-time error` occurs: 1715 1716.. code-block:: typescript 1717 :linenos: 1718 1719 function foo1 (n1: number, n2: number) // non-rest parameters 1720 { ... } 1721 let an_array = [1, 2] 1722 foo1 (...an_array) // compile-time error 1723 1724 function foo2 (n1: number, n2: string) // non-rest parameters 1725 { ... } 1726 let a_tuple: [number, string] = [1, "2"] 1727 foo2 (...a_tuple) // compile-time error 1728 1729.. index:: 1730 call site 1731 spread 1732 parameter 1733 tuple 1734 array 1735 1736| 1737 1738.. _Parenthesized Expression: 1739 1740Parenthesized Expression 1741************************ 1742 1743.. meta: 1744 frontend_status: Done 1745 1746The syntax of *parenthesized expression* is presented below: 1747 1748.. code-block:: abnf 1749 1750 parenthesizedExpression: 1751 '(' expression ')' 1752 ; 1753 1754Type and value of a parenthesized expression are the same as those of 1755the contained expression. 1756 1757.. index:: 1758 parenthesized expression 1759 type 1760 value 1761 contained expression 1762 1763| 1764 1765.. _this Expression: 1766 1767``this`` Expression 1768******************* 1769 1770.. meta: 1771 frontend_status: Done 1772 1773Keyword ``this`` can be used as an expression in the body of an instance 1774method of a class (see :ref:`Method Body`) or an interface (see 1775:ref:`Default Interface Method Declarations`). The type of *this* expression 1776is the appropriate class or interface type. 1777 1778The syntax of *this expression* is presented below: 1779 1780.. code-block:: abnf 1781 1782 thisExpression: 1783 'this' 1784 ; 1785 1786The keyword ``this`` can be used in a lambda expression only if it is allowed 1787in the context in which the lambda expression occurs. 1788 1789The keyword ``this`` in a *direct call* ``this(`` *arguments* ``)`` expression 1790can only be used in the explicit constructor call statement (see 1791:ref:`Explicit Constructor Call`). 1792 1793The keyword ``this`` can also be used in the body of a function with receiver 1794(see :ref:`Functions with Receiver`). The type of *this* expression is the 1795declared type of the parameter ``this`` in a function. 1796 1797A :index:`compile-time error` occurs if the keyword ``this`` appears elsewhere. 1798 1799.. index:: 1800 keyword this 1801 expression 1802 instance method 1803 method body 1804 class 1805 interface type 1806 lambda expression 1807 direct call expression 1808 constructor 1809 constructor call statement 1810 1811The keyword ``this`` used as a primary expression denotes a value that is a 1812reference to the following: 1813 1814- Object for which the instance method is called; or 1815- Object being constructed. 1816 1817The parameter ``this`` in a lambda body and in the surrounding context denote 1818the same value. 1819 1820The class of the actual object referred to at runtime can be ``T`` if ``T`` is 1821a class type, or a subclass of ``T`` (see :ref:`Subtyping`) . 1822 1823.. index:: 1824 keyword this 1825 primary expression 1826 value 1827 instance method 1828 instance method call 1829 object 1830 lambda body 1831 surrounding context 1832 class 1833 runtime 1834 class type 1835 class 1836 1837| 1838 1839.. _Field Access Expression: 1840 1841Field Access Expression 1842*********************** 1843 1844.. meta: 1845 frontend_status: Done 1846 1847*Field access expression* can access a field of an object to which an object 1848reference refers. The object reference can have different forms as described 1849in detail in :ref:`Accessing Current Object Fields` and in 1850:ref:`Accessing SuperClass Properties`. 1851 1852.. index:: 1853 field access expression 1854 access 1855 field 1856 object reference 1857 1858The syntax of *field access expression* is presented below: 1859 1860.. code-block:: abnf 1861 1862 fieldAccessExpression: 1863 objectReference ('.' | '?.') identifier 1864 ; 1865 1866A *field access expression* that contains '``?.``' (see :ref:`Chaining Operator`) 1867is called *safe field access* because it handles nullish object references 1868safely. 1869 1870If object reference evaluation completes abruptly, then so does the entire 1871field access expression. 1872 1873An object reference used to access a field must be a non-nullish reference 1874type ``T``. Otherwise, a :index:`compile-time error` occurs. 1875 1876A field access expression is valid if the identifier refers to an accessible 1877member field (see :ref:`Accessible`) in type ``T``. A :index:`compile-time error` 1878occurs otherwise. 1879 1880Type of a *field access expression* is the type of a member field. 1881 1882.. index:: 1883 access 1884 field 1885 field access expression 1886 safe field access 1887 nullish object reference 1888 object reference 1889 abrupt completion 1890 non-nullish type 1891 reference type 1892 member field 1893 accessible member field 1894 1895| 1896 1897.. _Accessing Current Object Fields: 1898 1899Accessing Current Object Fields 1900=============================== 1901 1902.. meta: 1903 frontend_status: Done 1904 1905The result of a field access expression is computed at runtime as described 1906below. 1907 1908a. *Static* field access (*objectReference* is evaluated in the form *typeReference*) 1909 1910The evaluation of *typeReference* is performed. The result of a *field access 1911expression* of a static field in a class is as follows: 1912 1913- ``variable`` if the field is not ``readonly``. The resultant value can 1914 be changed later. 1915 1916- ``value`` if the field is ``readonly``, except where *field access* occurs 1917 in a initializer block (see :ref:`Static Initialization`). 1918 1919.. index:: 1920 access 1921 runtime 1922 field access expression 1923 object reference expression 1924 evaluation 1925 static field access 1926 static field 1927 field access expression 1928 field access 1929 initializer block 1930 field 1931 readonly 1932 class 1933 1934b. *Instance* field access (*objectReference* is evaluated in the form *primaryExpression*) 1935 1936The evaluation of *primaryExpression* is performed. The result of *field 1937access expression* of an instance field in a class or interface is as follows: 1938 1939- ``variable`` if the field is not ``readonly``. The resultant value can 1940 be changed later. 1941 1942- ``value`` if the field is ``readonly``, except where *field access* occurs 1943 in a constructor (see :ref:`Constructor Declaration`). 1944 1945Only the *primaryExpression* type (not class type of an actual object 1946referred at runtime) is used to determine the field to be accessed. 1947 1948.. index:: 1949 instance field access 1950 field access 1951 field access expression 1952 interface 1953 readonly 1954 evaluation 1955 access 1956 runtime 1957 initializer 1958 instance initializer 1959 constructor 1960 field access 1961 class type 1962 1963| 1964 1965.. _Accessing SuperClass Properties: 1966 1967Accessing SuperClass Properties 1968=============================== 1969 1970.. meta: 1971 frontend_status: Done 1972 1973The form ``super.identifier`` is valid when accessing the superclass property 1974via accessor (see :ref:`Accessor Declarations`). 1975A :index:`compile-time error` occurs if identifier in 'super.identifier' 1976denotes a field. 1977 1978.. code-block:: typescript 1979 :linenos: 1980 1981 class Base { 1982 get property(): number { return 1 } 1983 set property(p: number) { } 1984 field = 1234 1985 } 1986 class Derived extends Base { 1987 get property(): number { return super.property } // OK 1988 set property(p: number) { super.property = 42 } // OK 1989 foo () { 1990 super.field = 42 // compile-time error 1991 console.log (super.field) // compile-time error 1992 } 1993 } 1994 1995.. index:: 1996 access 1997 superclass property 1998 identifier 1999 field 2000 2001| 2002 2003.. _Method Call Expression: 2004 2005Method Call Expression 2006********************** 2007 2008.. meta: 2009 frontend_status: Done 2010 2011A *method call expression* calls a static or instance method of a class or 2012an interface. Dynamic dispatch (see :ref:`Dispatch`) is used during program 2013execution to perform a call in case of an instance method. 2014 2015.. index:: 2016 method call expression 2017 static method 2018 instance method 2019 class 2020 interface 2021 2022The syntax of *method call expression* is presented below: 2023 2024.. code-block:: abnf 2025 2026 methodCallExpression: 2027 objectReference ('.' | '?.') identifier typeArguments? arguments block? 2028 ; 2029 2030The syntax form that has a block associated with the method call is a special 2031form called *trailing lambda call* (see :ref:`Trailing Lambdas` for details). 2032 2033A method call with '``?.``' (see :ref:`Chaining Operator`) is called a 2034*safe method call* because it handles nullish values safely. 2035 2036Resolving a method at compile time is more complicated than resolving a field 2037because method overloading (see :ref:`Class Method Overloading`) can occur. 2038 2039There are several steps that determine and check the method to be called at 2040compile time (see :ref:`Step 1 Selection of Type to Use`, 2041:ref:`Step 2 Selection of Method`, and 2042:ref:`Step 3 Checking Method Modifiers`). 2043 2044.. index:: 2045 syntax 2046 block 2047 trailing lambda call 2048 method call 2049 safe method call 2050 nullish value 2051 method resolution 2052 method overloading 2053 compile time 2054 field resolution 2055 2056| 2057 2058.. _Step 1 Selection of Type to Use: 2059 2060Step 1: Selection of Type to Use 2061================================ 2062 2063.. meta: 2064 frontend_status: Done 2065 2066The *object reference* is used to determine the type in which to search for the 2067method. Three forms of *object reference* are possible: 2068 2069.. table:: 2070 :widths: 30, 70 2071 2072 ============================== ================================================================= 2073 Form of Object Reference Type to Use 2074 ============================== ================================================================= 2075 ``typeReference`` Type denoted by ``typeReference``. 2076 ``expression`` of type *T* ``T`` if ``T`` is a class, interface, or union; ``T``’s constraint (:ref:`Type Parameter Constraint`) if ``T`` is a type parameter. A :index:`compile-time error` occurs otherwise. 2077 ``super`` The superclass of the class that contains the method call. 2078 ============================== ================================================================= 2079 2080.. index:: 2081 type 2082 type parameter 2083 object reference 2084 method 2085 constraint 2086 superclass 2087 method call 2088 2089| 2090 2091.. _Step 2 Selection of Method: 2092 2093Step 2: Selection of Method 2094=========================== 2095 2096.. meta: 2097 frontend_status: Done 2098 2099After the type to use is known, the method to call must be determined. |LANG| 2100supports overloading, and more than one method can be accessible under the 2101method name used in the call. 2102 2103All accessible methods (see :ref:`Accessible`) are called 2104*potentially applicable candidates*, and :ref:`Overload Resolution` is used to 2105select the method to call. If *overload resolution* can definitely select a 2106single method, then this method is called. 2107A :index:`compile-time error` occurs in the following cases: 2108 2109- If no method is available for the call, or 2110- If there is more than one applicable method, thus causing ambiguity. 2111 2112.. index:: 2113 overload resolution 2114 method call 2115 potentially applicable candidate 2116 accessible method 2117 access 2118 2119| 2120 2121.. _Step 3 Checking Method Modifiers: 2122 2123Step 3: Checking Method Modifiers 2124================================= 2125 2126.. meta: 2127 frontend_status: Done 2128 2129In this step, the single method to call is known, and the following set of 2130semantic checks must be performed: 2131 2132- If the method call has the form ``typeReference.identifier``, then 2133 ``typeReference`` refers to a class, and the method must be declared 2134 ``static``. Otherwise, a :index:`compile-time error` occurs. 2135 2136- If the method call has the form ``expression.identifier``, then the method 2137 must not be declared ``static``. Otherwise, a :index:`compile-time error` 2138 occurs. 2139 2140- If the method call has the form ``super.identifier``, then the method must 2141 not be declared ``abstract`` or ``static``. Otherwise, a 2142 :index:`compile-time error` occurs. 2143 2144.. index:: 2145 method call 2146 semantic check 2147 static method call 2148 abstract method call 2149 type argument 2150 2151| 2152 2153.. _Type of Method Call Expression: 2154 2155Type of Method Call Expression 2156============================== 2157 2158.. meta: 2159 frontend_status: Done 2160 2161Type of a *method call expression* is the return type of the method. 2162 2163.. code-block:: typescript 2164 :linenos: 2165 2166 class A { 2167 static method() { console.log ("Static method() is called") } 2168 method() { console.log ("Instance method() is called") } 2169 } 2170 2171 2172 let x = A.method() // compile-time error as void cannot be used as type annotation 2173 A.method () // OK 2174 let y = new A.method() // compile-time error as void cannot be used as type annotation 2175 new A.method() // OK 2176 2177.. index:: 2178 method call expression 2179 method return type 2180 type annotation 2181 2182| 2183 2184.. _Function Call Expression: 2185 2186Function Call Expression 2187************************ 2188 2189.. meta: 2190 frontend_status: Done 2191 2192*Function call expression* is used to call a function (see 2193:ref:`Function Declarations`), a variable of a function type 2194(:ref:`Function Types`), or a lambda expression (see :ref:`Lambda Expressions`). 2195 2196The syntax of *function call expression* is presented below: 2197 2198.. code-block:: abnf 2199 2200 functionCallExpression: 2201 expression ('?.' | typeArguments)? arguments block? 2202 ; 2203 2204A special syntactic form that contains a block associated with the function 2205call is called *trailing lambda call* (see :ref:`Trailing Lambdas` for details). 2206 2207A :index:`compile-time error` occurs if the expression type is one of the 2208following: 2209 2210- Different than the function type; 2211- Nullish type without '``?.``' (see :ref:`Chaining Operator`). 2212 2213.. index:: 2214 function call expression 2215 function call 2216 function type 2217 trailing lambda call 2218 lambda expression 2219 expression type 2220 function type 2221 nullish type 2222 chaining operator 2223 2224If the operator '``?.``' (see :ref:`Chaining Operator`) is present, and the 2225*expression* evaluates to a nullish value, then: 2226 2227- *Arguments* are not evaluated; 2228- Call is not performed; and 2229- Result of *functionCallExpression* is not produced as a consequence. 2230 2231The function call is *safe* because it handles nullish values properly. 2232 2233.. index:: 2234 chaining operator 2235 expression 2236 evaluation 2237 nullish value 2238 argument 2239 semantic correctness check 2240 undefined 2241 function call 2242 2243The following important situations depend on the form of expression in a call, 2244and require different semantic checks: 2245 2246- The form of expression in the call is *qualifiedName*, and *qualifiedName* 2247 refers to an accessible function (:ref:`Function Declarations`), or to a set 2248 of accessible overloaded functions. 2249 2250 In this case, all accessible functions (see :ref:`Accessible`) are 2251 *potentially applicable candidates*. :ref:`Overload Resolution` is used to 2252 select the function to call. If *overload resolution* can definitely select a 2253 single function, then this function is called. 2254 2255A :index:`compile-time error` occurs in the following cases: 2256 2257- If no function is available to call; 2258- If there is more than one applicable function, thus causing ambiguity; or 2259- All other forms of expression. 2260 2261 In this case, *overload resolution* is not required as the expression 2262 determines the entity to call unambiguously. Semantic check is performed 2263 in accordance with :ref:`Compatibility of Call Arguments`. 2264 2265.. index:: 2266 call 2267 expression 2268 qualified name 2269 accessible function 2270 overloaded function 2271 overload resolution 2272 expression 2273 semantic check 2274 compatibility 2275 function call 2276 potentially applicable candidate 2277 accessibility 2278 qualified name 2279 function 2280 2281The example below represents different forms of function calls: 2282 2283.. code-block:: typescript 2284 :linenos: 2285 2286 function foo() { console.log ("Function foo() is called") } 2287 foo() // function call uses function name to call it 2288 2289 call (foo) // top-level function passed 2290 call ((): void => { console.log ("Lambda is called") }) // lambda is passed 2291 call (A.method) // static method 2292 call ((new A).method) // instance method is passed 2293 2294 class A { 2295 static method() { console.log ("Static method() is called") } 2296 method() { console.log ("Instance method() is called") } 2297 } 2298 2299 function call (callee: () => void) { 2300 callee() // function call uses parameter name to call any functional object passed as an argument 2301 } 2302 2303 ((): void => { console.log ("Lambda is called") }) () // function call uses lambda expression to call it 2304 2305 let x = foo() // compile-time error as void cannot be used as type annotation 2306 2307Type of a *function call expression* is the return type of the function. 2308 2309.. index:: 2310 function call 2311 function call expression 2312 return type 2313 function 2314 2315| 2316 2317.. _Indexing Expressions: 2318 2319Indexing Expressions 2320******************** 2321 2322.. meta: 2323 frontend_status: Done 2324 2325*Indexing expressions* are used to access elements of arrays (see 2326:ref:`Array Types`), strings (see :ref:`Type string`) and 2327``Record`` instances (see :ref:`Record Utility Type`). 2328Indexing expressions can also be applied to instances of indexable types (see 2329:ref:`Indexable Types`). 2330 2331The syntax of *indexing expression* is presented below: 2332 2333.. code-block:: abnf 2334 2335 indexingExpression: 2336 expression ('?.')? '[' expression ']' 2337 ; 2338 2339Any *indexing expression* has two subexpressions as follows: 2340 2341- *Object reference expression* before the left bracket; and 2342- *Index expression* inside the brackets. 2343 2344.. index:: 2345 indexing expression 2346 indexable type 2347 access 2348 array element 2349 array type 2350 subexpression 2351 object reference expression 2352 index expression 2353 bracket 2354 2355If the operator '``?.``' (see :ref:`Chaining Operator`) is present in an 2356indexing expression, then: 2357 2358- If an object reference expression is not of a nullish type, then the 2359 chaining operator has no effect. 2360- Otherwise, object reference expression must be checked to nullish 2361 value. If the value is ``undefined`` or ``null``, 2362 then the evaluation of the entire surrounding *primary expression* stops. 2363 The result of the entire primary expression is then ``undefined``. 2364 2365If no '``?.``' is present in an indexing expression, then object reference 2366expression must be an array type or the ``Record`` type. Otherwise, a 2367:index:`compile-time error` occurs. 2368 2369.. index:: 2370 chaining operator 2371 operator 2372 indexing expression 2373 object reference expression 2374 expression 2375 primary expression 2376 nullish type 2377 record type 2378 reference expression 2379 nullish value 2380 2381| 2382 2383.. _Array Indexing Expression: 2384 2385Array Indexing Expression 2386========================= 2387 2388.. meta: 2389 frontend_status: Partly 2390 todo: implement floating point index support - #14001 2391 2392*Index expression* for array indexing must be of a numeric type (see 2393:ref:`Numeric Types`). 2394 2395If an *index expression* is of type ``number`` or other floating-point type, 2396and the fractional part differs from 0, then errors occur as follows: 2397 2398- A runtime error, if the situation is identified during program execution; 2399 and 2400- A :index:`compile-time error`, if the situation is detected during 2401 compilation. 2402 2403.. index:: 2404 array indexing 2405 numeric type 2406 index expression 2407 floating-point type 2408 runtime error 2409 compilation 2410 2411A numeric types conversion (see :ref:`Widening Numeric Conversions`) is 2412performed on an *index expression* to ensure that the resultant type is ``int``. 2413Otherwise, a :index:`compile-time error` occurs. 2414 2415If the chaining operator '``?.``' (see :ref:`Chaining Operator`) is present, 2416and after its application the type of *object reference expression* 2417is an *array type*, 2418then it makes a valid *array reference expression*, and the type 2419of the array indexing expression is ``T``. 2420 2421The result of an array indexing expression is a variable of type ``T`` (i.e., an 2422element of the array selected by the value of that *index expression*). 2423 2424It is essential that, if type ``T`` is a reference type, then the fields of 2425array elements can be modified by changing the resultant variable fields: 2426 2427.. index:: 2428 numeric types conversion 2429 index expression 2430 chaining operator 2431 object reference expression 2432 array type 2433 array reference expression 2434 array indexing expression 2435 variable 2436 reference type 2437 2438 2439.. code-block:: typescript 2440 :linenos: 2441 2442 let names: string[] = ["Alice", "Bob", "Carol"] 2443 console.log(names[1]) // prints Bob 2444 names[1] = "Martin" 2445 console.log(names[1]) // prints Martin 2446 2447 class RefType { 2448 field: number = 42 2449 } 2450 const objects: RefType[] = [new RefType(), new RefType()] 2451 const object = objects [1] 2452 object.field = 777 // change the field in the array element 2453 console.log(objects[0].field) // prints 42 2454 console.log(objects[1].field) // prints 777 2455 2456 let an_array = [1, 2, 3] 2457 let element = an_array [3.5] // Compile-time error 2458 function foo (index: number) { 2459 let element = an_array [index] 2460 // Runtime-time error if index is not integer 2461 } 2462 2463An array indexing expression evaluated at runtime behaves as follows: 2464 2465- Object reference expression is evaluated first. 2466- If the evaluation completes abruptly, then so does the indexing 2467 expression, and the index expression is not evaluated. 2468- If the evaluation completes normally, then the index expression is evaluated. 2469 The resultant value of the object reference expression refers to an array. 2470- If the index expression value of an array is less than zero, greater than 2471 or equal to that array’s *length*, then the ``ArrayIndexOutOfBoundsError`` 2472 is thrown. 2473- Otherwise, the result of the array access is a type ``T`` variable within 2474 the array selected by the value of the index expression. 2475 2476.. code-block:: typescript 2477 :linenos: 2478 2479 function setElement(names: string[], i: number, name: string) { 2480 names[i] = name // run-time error, if 'i' is out of bounds 2481 } 2482 2483.. index:: 2484 array indexing expression 2485 index expression 2486 evaluation 2487 runtime 2488 array 2489 object reference expression 2490 abrupt completion 2491 normal completion 2492 reference expression 2493 variable 2494 2495| 2496 2497.. _String Indexing Expression: 2498 2499_String Indexing Expression 2500=========================== 2501 2502.. meta: 2503 frontend_status: Partly 2504 todo: return type is string 2505 2506*Index expression* for array indexing must be of a numeric type (see 2507:ref:`Numeric Types`), the rules are the same as for 2508:ref:`Array Indexing Expression`. 2509 2510If the index expression value of an array is less than zero, greater than 2511or equal to that string’s *length*, then the ``ArrayIndexOutOfBoundsError`` 2512is thrown. 2513 2514.. index:: 2515 string indexing 2516 value 2517 type 2518 2519.. code-block:: typescript 2520 :linenos: 2521 2522 console.log("abc"[1]]) // prints: b 2523 console.log("abc"[3]]) // run-time exception 2524 2525The result of an string indexing expression is a value of ``string`` type. 2526 2527**Note.** String value is immutable, it is not allowed to change a value of 2528string element by indexing. 2529 2530.. code-block:: typescript 2531 :linenos: 2532 2533 let x = "abc" 2534 x[1] = "d" // compile-time error, string value is immutable 2535 2536| 2537 2538.. _Record Indexing Expression: 2539 2540Record Indexing Expression 2541========================== 2542 2543.. meta: 2544 frontend_status: Done 2545 2546*Indexing expression* for a type ``Record<Key, Value>`` (see 2547:ref:`Record Utility Type`) allows getting or setting a value of type ``Value`` 2548at an index specified by the expression of type ``Key``. 2549 2550The following two cases are to be considered separately: 2551 25521. Type ``Key`` is a union that contains literal types only; 25532. Other cases. 2554 2555**Case 1.** If type ``Key`` is a union that contains literal types only, then 2556an *index expression* can only be one of the literals listed in the type. 2557The result of the indexing expression is of type ``Value``. 2558 2559.. code-block-meta: 2560 2561.. code-block:: typescript 2562 :linenos: 2563 2564 type Keys = 'key1' | 'key2' | 'key3' 2565 2566 let x: Record<Keys, number> = { 2567 'key1': 1, 2568 'key2': 2, 2569 'key3': 4, 2570 } 2571 let y = x['key2'] // y value is 2 2572 2573.. index:: 2574 index expression 2575 indexing expression 2576 key 2577 literal type 2578 literal 2579 value 2580 type 2581 2582A :index:`compile-time error` occurs if an index expression is not a valid 2583literal: 2584 2585.. code-block:: typescript 2586 :linenos: 2587 2588 console.log(x['key4']) // compile-time error 2589 x['another key'] = 5 // compile-time error 2590 2591The compiler guarantees that an object of ``Record<Key, Value>`` for this type 2592``Key`` contains values for all ``Key`` keys. 2593 2594**Case 2.** An *index expression* has no restriction. 2595The result of an indexing expression is of type ``Value | undefined``. 2596 2597.. index:: 2598 index expression 2599 indexing expression 2600 literal 2601 compiler 2602 object 2603 key 2604 restriction 2605 2606 2607.. code-block-meta: 2608 2609.. code-block:: typescript 2610 :linenos: 2611 2612 let x: Record<number, string> = { 2613 1: "hello", 2614 2: "buy", 2615 } 2616 2617 function foo(n: number): string | undefined { 2618 return x[n] 2619 } 2620 2621 function bar(n: number): string { 2622 let s = x[n] 2623 if (s == undefined) { return "no" } 2624 return s! 2625 } 2626 2627 foo(3) // prints "undefined" 2628 bar(3) // prints "no" 2629 2630 let y = x[3] 2631 2632.. index:: 2633 index expression 2634 literal 2635 key 2636 compiler 2637 value 2638 indexing expression 2639 2640Type of *y* in the code above is ``string | undefined``. The value of 2641*y* is ``undefined``. 2642 2643An indexing expression evaluated at runtime behaves as follows: 2644 2645- Object reference expression is evaluated first. 2646- If the evaluation completes abruptly, then so does the indexing 2647 expression, and the index expression is not evaluated. 2648- If the evaluation completes normally, then the index expression is 2649 evaluated. 2650 The resultant value of the object reference expression refers to a ``record`` 2651 instance. 2652- If the ``record`` instance contains a key defined by the index expression, 2653 then the result is the value mapped to the key. 2654- Otherwise, the result is the literal ``undefined``. 2655 2656Syntactically, the *record indexing expression* can be written by using a field 2657access notation (see :ref:`Field Access Expression`) if its *index expression* 2658is formed as an *identifier* of type *string*. 2659 2660.. code-block:: typescript 2661 :linenos: 2662 2663 type Keys = 'key1' | 'key2' | 'key3' 2664 2665 let x: Record<Keys, number> = { 2666 'key1': 1, 2667 'key2': 2, 2668 'key3': 4, 2669 } 2670 console.log(x.key2) // the same as console.log(x['key2']) 2671 x.key2 = 8 // the same as x['key2'] = 8 2672 console.log(x.key2) // the same as console.log(x['key2']) 2673 2674 2675 2676.. index:: 2677 type 2678 value 2679 reference type 2680 key 2681 indexing expression 2682 index expression 2683 object reference expression 2684 abrupt completion 2685 normal completion 2686 literal 2687 record instance 2688 mapped value 2689 2690| 2691 2692.. _Chaining Operator: 2693 2694Chaining Operator 2695***************** 2696 2697.. meta: 2698 frontend_status: Done 2699 2700The *chaining operator* '``?.``' is used to effectively access values of 2701nullish types. It can be used in the following contexts: 2702 2703- :ref:`Field Access Expression`, 2704- :ref:`Method Call Expression`, 2705- :ref:`Function Call Expression`, 2706- :ref:`Indexing Expressions`. 2707 2708If the value of the expression to the left of '``?.``' is ``undefined`` or 2709``null``, then the evaluation of the entire surrounding *primary expression* 2710stops. The result of the entire primary expression is then ``undefined``. Thus 2711the type of the entire primary expression is the union ``undefined`` | 2712*non-nullish type of the entire primary expression*: 2713 2714.. index:: 2715 chaining operator 2716 field access 2717 access 2718 value 2719 nullish type 2720 primary expression 2721 non-nullish type 2722 2723.. code-block-meta: 2724 2725.. code-block:: typescript 2726 :linenos: 2727 2728 class Person { 2729 name: string 2730 spouse?: Person = undefined 2731 constructor(name: string) { 2732 this.name = name 2733 } 2734 } 2735 2736 let bob = new Person("Bob") 2737 console.log(bob.spouse?.name) // prints "undefined" 2738 // type of bob.spouse?.name is undefined|string 2739 2740 bob.spouse = new Person("Alice") 2741 console.log(bob.spouse?.name) // prints "Alice" 2742 // type of bob.spouse?.name is undefined|string 2743 2744If an expression is not of a nullish type, then the chaining operator has 2745no effect. 2746 2747A :index:`compile-time error` occurs if a chaining operator is placed in the 2748context where a variable is expected, e.g., in the left-hand-side expression of 2749an assignment (see :ref:`Assignment`) or expression 2750(see :ref:`Postfix Increment`, :ref:`Postfix Decrement`, 2751:ref:`Prefix Increment` or :ref:`Prefix Decrement`). 2752 2753.. index:: 2754 expression 2755 chaining operator 2756 nullish value 2757 nullish type 2758 assignment 2759 postfix 2760 prefix 2761 decrement 2762 increment 2763 function call 2764 method call 2765 primary expression 2766 evaluation 2767 access 2768 value 2769 2770| 2771 2772.. _New Expressions: 2773 2774``New`` Expressions 2775******************* 2776 2777.. meta: 2778 frontend_status: Done 2779 2780There are two syntactical forms of the *new expression*: 2781 2782.. code-block:: abnf 2783 2784 newExpression: 2785 newClassInstance 2786 | newArrayInstance 2787 ; 2788 2789Type of a *new expression* is ether ``class`` or ``array``. 2790 2791A *new class instance expression* creates a new object that is an instance 2792of the specified class and it is described in full details below. 2793 2794The creation of array instances is an experimental feature discussed in 2795:ref:`Resizable Array Creation Expressions`. 2796 2797.. index:: 2798 syntactical form 2799 expression 2800 expression type 2801 instance 2802 instantiation 2803 class instance creation expression 2804 array instance 2805 array creation expression 2806 2807The syntax of *new class instance expression* is presented below: 2808 2809.. code-block:: abnf 2810 2811 newClassInstance: 2812 'new' typeArguments? typeReference arguments? 2813 ; 2814 2815*Class instance creation expression* specifies a class to be instantiated. 2816It optionally lists all actual arguments for the constructor. 2817 2818.. code-block:: typescript 2819 :linenos: 2820 2821 class A { 2822 constructor(p: number) {} 2823 } 2824 2825 new A(5) // create an instance and call constructor 2826 const a = new A(6) /* create an instance, call constructor and store 2827 created and initialized instance in 'a' */ 2828 2829 2830*Class instance creation expression* can throw an error 2831(see :ref:`Error Handling`, :ref:`Constructor Declaration`). 2832 2833.. index:: 2834 class instance creation expression 2835 instantiation 2836 instance 2837 constructor 2838 initialization 2839 2840The execution of a class instance creation expression is performed as follows: 2841 2842- New instance of class is created; 2843- Constructor of class is called to fully initialize the created 2844 instance. 2845 2846The validity of the constructor call is similar to the validity of the method 2847call as discussed in :ref:`Step 2 Selection of Method`, except the cases 2848discussed in :ref:`Constructor Body`. 2849 2850A :index:`compile-time error` occurs if ``typeReference`` is a type parameter. 2851 2852**Note**. If a *class instance creation expression* with no argument is used 2853as object reference in a method call expression, then empty parentheses 2854'*()*' are to be used. 2855 2856.. code-block:: typescript 2857 :linenos: 2858 2859 class A { method() {} } 2860 2861 new A.method() // compile-time error 2862 new A().method() // OK 2863 let a = new A // OK 2864 2865 2866.. index:: 2867 class instance creation expression 2868 instance 2869 instantiation 2870 constructor 2871 initialization 2872 type parameter 2873 method call expression 2874 parenthesis 2875 2876| 2877 2878.. _InstanceOf Expression: 2879 2880``InstanceOf`` Expression 2881************************* 2882 2883.. meta: 2884 frontend_status: Done 2885 2886The syntax of *instanceof expression* is presented below: 2887 2888.. code-block:: abnf 2889 2890 instanceOfExpression: 2891 expression 'instanceof' type 2892 ; 2893 2894Any ``instanceof`` expression in the form ``expr instanceof T`` is of type ``boolean``. 2895 2896.. index:: 2897 instanceof expression 2898 operand 2899 operator 2900 instanceof operator 2901 2902The result of an ``instanceof`` expression is ``true`` if the *actual type* of 2903evaluated ``expr`` is a subtype of ``T`` (see :ref:`Subtyping`). Otherwise, 2904the result is ``false``. 2905 2906A :index:`compile-time error` occurs if type ``T`` is not preserved by 2907:ref:`Type Erasure`. 2908 2909*Generic type* (see :ref:`Generics`) in the form of *type name* (see :ref:`Type References`) 2910can be used as ``T`` operand of an ``instanceof`` expression. In this case, 2911the check is performed against the *type name*, and *type parameters* are 2912ignored. *Instantiated generic types* (see :ref:`Explicit Generic Instantiations`) 2913cannot be used because the ``T`` operand of an ``instanceof`` must be preserved 2914by :ref:`Type Erasure`. 2915 2916.. code-block:: typescript 2917 :linenos: 2918 2919 class C<T> { 2920 foo() { 2921 console.log(this instanceof C) // true 2922 console.log(this instanceof C<T>) // compile-time error 2923 } 2924 } 2925 2926 let c = new C<number> 2927 c.foo() 2928 2929The ``type`` of an ``instanceof`` expression is used for *smart typing* 2930(see :ref:`Smart Types`) if applicable. 2931 2932.. index:: 2933 instanceof expression 2934 subtype 2935 type erasure 2936 smart typing 2937 instantiated generic type 2938 generic type 2939 type name 2940 type parameter 2941 generic instantiation 2942 2943| 2944 2945.. _Cast Expression: 2946 2947``Cast`` Expression 2948******************* 2949 2950.. meta: 2951 frontend_status: Done 2952 2953*Cast expression* in the form ``expr instanceof target`` applies *cast operator* 2954``as`` to an expression by issuing a value of a specified ``target`` type. The 2955syntax of *cast expression* is as follows: 2956 2957.. code-block:: abnf 2958 2959 castExpression: 2960 expression 'as' type 2961 ; 2962 2963.. code-block:: typescript 2964 :linenos: 2965 2966 class X {} 2967 2968 let x1 : X = new X() 2969 let ob : Object = x1 as Object 2970 let x2 : X = ob as X 2971 2972.. index:: 2973 cast expression 2974 operand 2975 instanceof 2976 cast operator 2977 2978The following cases are considered for an *expr as T* in a sequence as follows: 2979 2980- If ``expr`` is a constant expression (see :ref:`Constant Expressions`), 2981 :ref:`Array literal`, or :ref:`Object Literal`, then an attempt is made to 2982 apply :ref:`Type Inference in Cast Expression`; 2983 2984- If the ``target`` type is an enumeration type (see :ref:`Enumerations`), 2985 then an attempt is made to apply :ref:`Casting to Enumeration`; 2986 2987- Otherwise, :ref:`Runtime Checking in Cast Expression` is applied. 2988 2989.. index:: 2990 cast operator 2991 cast expression 2992 expression 2993 conversion 2994 value 2995 runtime 2996 casting context 2997 type 2998 2999Cast expression type is always the ``target`` type. 3000 3001A :index:`compile-time error` occurs if the ``target`` type is type ``never`` 3002as it can cause a type-safety violation as follows: 3003 3004.. code-block:: typescript 3005 :linenos: 3006 3007 1 as never // compile-time error 3008 3009.. index:: 3010 type never 3011 type-safety violation 3012 target type 3013 cast expression 3014 3015The result of a cast expression is a value, not a variable (even if the operand 3016expression is a variable). 3017 3018A :index:`compile-time error` occurs if the cast operator cannot convert the 3019compile-time type of the operand to the ``target`` type specified by the cast 3020operator. 3021 3022.. index:: 3023 cast expression 3024 target type 3025 value 3026 variable 3027 operand expression 3028 variable 3029 operand value 3030 cast operator 3031 casting conversion 3032 3033| 3034 3035.. _Type Inference in Cast Expression: 3036 3037Type Inference in Cast Expression 3038================================= 3039 3040The following combinations of ``expr`` and ``target`` are considered for the 3041``expr as target`` expression: 3042 3043- ``expr`` is a constant expression (see :ref:`Constant Expressions`) of a 3044 numeric type, and ``target`` is a numeric type. A :index:`compile-time error` 3045 occurs if the value of ``expr`` does not belong to the ``target``; 3046 3047- ``expr`` is a constant expression (see :ref:`Constant Expressions`), and 3048 ``target`` is an enumeration type. A :index:`compile-time error` occurs 3049 if the value of ``expr`` does not equal a value of an enumeration type 3050 constant; 3051 3052- ``expr`` is an :ref:`Array Literal`, and ``target`` is an *array type* or 3053 a *tuple type* (see :ref:`Array Literal Type Inference from Context` for 3054 detail); 3055 3056- ``expr`` is an :ref:`Object Literal`, and ``target`` is *class type*, 3057 *interface type*, or :ref:`Record Utility Type` (see the subsections of 3058 :ref:`Object Literal` for detail). 3059 3060This kind of a *cast expression* results in inferring the target type for 3061``expr``, and never causes a runtime error by itself. However, the evaluation 3062of array literal elements or object literal properties can cause a runtime error. 3063 3064Casting for constant expressions of *numeric types* is represented in the 3065example below: 3066 3067.. code-block:: typescript 3068 :linenos: 3069 3070 let x = 1 as byte // ok 3071 let y = 128 as byte // compile-time error 3072 3073Casting for constant expressions to enumeration types is represented in the 3074example below: 3075 3076.. code-block:: typescript 3077 :linenos: 3078 3079 enum NumE {A, B} 3080 enums StrE {S1 = "aaa", S2 = "bbb"} 3081 3082 let x = 1 as NumE // ok, it is E.B 3083 let y = 2 as NumE // compile-time error 3084 3085 let u = "aaa" as StrE // ok, it is StrE.S1 3086 let v = "abc" as StrE // compile-time error 3087 3088Casting for array literals of *numeric types* is represented in the example 3089below: 3090 3091.. code-block:: typescript 3092 :linenos: 3093 3094 let a = [1, 2] as double[] // ok, [1.0, 2.0] 3095 let b = [1, 2] as double // compile-time error, wrong target type 3096 let c = [1, "cc"] as double[] // compile-time error, wrong element type 3097 let d = [1, "cc"] as [double, string] // ok 3098 let e = [1.0, "cc"] as [int, string] // compile-time error, wrong element type 3099 3100**Note.** *Assignability* check is applied to the elements of an array literal. 3101 3102Examples with object literals are provided in :ref:`Object literal`. 3103 3104| 3105 3106.. _Casting to Enumeration: 3107 3108Casting to Enumeration 3109====================== 3110 3111There are two cases where an ``expr as target`` expression is used to convert 3112an expression value to the ``target`` enumeration type: 3113 3114- If the *enumeration base type* is an integer type, and the 3115 expression is of integer type; or 3116 3117- If the *enumeration base type* is type ``string``, and the 3118 expression is of string type. 3119 3120In both cases, the check is performed at runtime: 3121 3122- If the value of ``expr`` is the value of some constant of the enumeration 3123 type, then the value is converted to the enumeration type; 3124 3125- Otheriwise, a runtime error occurs. 3126 3127.. code-block:: typescript 3128 :linenos: 3129 3130 enum NumE {A, B} 3131 3132 function foo(x: int): NumE { 3133 return x as NumE 3134 } 3135 3136 foo(1) // ok 3137 foo(2) // runtime error occurs in 'foo' 3138 3139| 3140 3141.. _Runtime Checking in Cast Expression: 3142 3143Runtime Checking in Cast Expression 3144=================================== 3145 3146If none of the previous kinds of *cast expression* can be applied, then 3147``expr as target`` checks that the type of ``expr`` is a subtype of 3148``target`` (see :ref:`Subtyping`). 3149 3150The result of an ``as`` expression is the result of the evaluated ``expr`` 3151if the *actual type* of ``expr`` is a subtype of ``target`` (see :ref:`Subtyping`). 3152Otherwise, ``ClassCastError`` is thrown. 3153 3154If ``target`` type is not preserved by :ref:`Type Erasure`, the check is 3155performed against an *effective type* of the ``target`` type. As, 3156in the described case an *effective type* is less specific than ``target``, 3157usage of the resulting value may lead to type violations and 3158``ClassCastError`` thrown as a consequence. See :ref:`Type Erasure` for more details. 3159 3160Semantically, a *cast expression* of this kind is coupled tightly with 3161:ref:`Instanceof Expression`: 3162 3163- If the result of ``x instanceof T`` is ``true``, then ``x as T`` never 3164 causes a runtime error; 3165 3166- If ``x instanceof T`` causes a :index:`compile-time error`, then 3167 :ref:`Type Erasure` affects the semantics of ``x as T``. 3168 3169- If otherwise the result of ``x instanceof T`` is ``false``, then ``x as T`` 3170 causes ``ClassCastError`` thrown at runtime. 3171 3172This situation is represented in the following example: 3173 3174.. code-block:: typescript 3175 :linenos: 3176 3177 function foo (x: Object) { 3178 console.log(x as string) 3179 } 3180 3181 foo("aa") // OK 3182 foo(1) // runtime error is thrown in foo 3183 3184:ref:`Instanceof Expression` can be used to prevent runtime errors. Moreover, 3185in many cases :ref:`Instanceof Expression` makes *cast conversion* unnecessary 3186as *smart casting* is applied (see :ref:`Smart Types`): 3187 3188.. code-block:: typescript 3189 :linenos: 3190 3191 class Person { 3192 name: string 3193 constructor (name: string) { this.name = name } 3194 } 3195 3196 function printName(x: Object) { 3197 if (x instanceof Person) { 3198 // no need to cast, type of 'x' is 'Person' here 3199 console.log(x.name) 3200 } else { 3201 console.log("no name") 3202 } 3203 } 3204 3205 printName(new Person("Bob")) // output: Bob 3206 printName(1) // output: no name 3207 3208| 3209 3210.. _TypeOf Expression: 3211 3212``TypeOf`` Expression 3213********************* 3214 3215.. meta: 3216 frontend_status: Done 3217 3218The syntax of *typeof expression* is presented below: 3219 3220.. code-block:: abnf 3221 3222 typeOfExpression: 3223 'typeof' expression 3224 ; 3225 3226Any ``typeof`` expression is of type ``string``. 3227 3228If *typeof expression* refers to a name of the overloaded function or method, 3229then a :index:`compile-time error` occurs. 3230 3231The evaluation of a *typeof expression* starts with the ``expression`` 3232evaluation. If this evaluation causes an error, then the ``typeof`` expression 3233evaluation terminates abruptly. Otherwise, the value of a ``typeof expression`` 3234is defined as follows: 3235 32361. **Expression type defined at compile time** 3237 3238.. index:: 3239 typeof expression 3240 type string 3241 evaluation 3242 compile time 3243 3244+---------------------------------+-------------------------+-----------------------------+ 3245| Type of Expression | Resulting String | Code Example | 3246+=================================+=========================+=============================+ 3247| ``number`` | "number" | .. code-block:: typescript | 3248| | | | 3249| | | let n: number = ... | 3250| | | typeof n | 3251+---------------------------------+-------------------------+-----------------------------+ 3252| ``string`` | "string" | .. code-block:: typescript | 3253| | | | 3254| | | let s: string = ... | 3255| | | typeof s | 3256+---------------------------------+-------------------------+-----------------------------+ 3257| ``boolean`` | "boolean" | .. code-block:: typescript | 3258| | | | 3259| | | let b: boolean = ... | 3260| | | typeof b | 3261+---------------------------------+-------------------------+-----------------------------+ 3262| ``bigint`` | "bigint" | .. code-block:: typescript | 3263| | | | 3264| | | let b: bigint = ... | 3265| | | typeof b | 3266+---------------------------------+-------------------------+-----------------------------+ 3267| any class or interface | "object" | .. code-block:: typescript | 3268| | | | 3269| | | let a: Object = ... | 3270| | | typeof a | 3271+---------------------------------+-------------------------+-----------------------------+ 3272| any function type | "function" | .. code-block:: typescript | 3273| | | | 3274| | | let f: () => void = ... | 3275| | | typeof f | 3276+---------------------------------+-------------------------+-----------------------------+ 3277| ``undefined`` | "undefined" | .. code-block:: typescript | 3278| | | | 3279| | | typeof undefined | 3280+---------------------------------+-------------------------+-----------------------------+ 3281| ``null`` | "object" | .. code-block:: typescript | 3282| | | | 3283| | | typeof null | 3284+---------------------------------+-------------------------+-----------------------------+ 3285| ``T|null``, when ``T`` is a | "object" | .. code-block:: typescript | 3286| class (but not Object - | | | 3287| see next table), | | class C {} | 3288| interface or array | | let x: C | null = ... | 3289| | | typeof x | 3290+---------------------------------+-------------------------+-----------------------------+ 3291| ``enum`` | "number" or "string", | .. code-block:: typescript | 3292| | depending of constant | | 3293| | type | enum C {R, G, B} | 3294| | | let c: C = ... | 3295| | | typeof c | 3296+---------------------------------+-------------------------+-----------------------------+ 3297| Numeric types: | "number" | .. code-block:: typescript | 3298| | | | 3299| | | let x: byte = ... | 3300| ``byte``, ``short``, ``int``, | | typeof x | 3301| ``long``, ``float``, ``double`` | | ... | 3302+---------------------------------+-------------------------+-----------------------------+ 3303 3304| 3305 33062. **Expression type defined at runtime** 3307 3308+------------------------+-----------------------------+ 3309| Type of Expression | Code Example | 3310+========================+=============================+ 3311| Object | .. code-block:: typescript | 3312| | | 3313| | function f(o: Object) { | 3314| | typeof o | 3315| | } | 3316+------------------------+-----------------------------+ 3317| union type | .. code-block:: typescript | 3318| | | 3319| | function f(p:A|B) { | 3320| | typeof p | 3321| | } | 3322+------------------------+-----------------------------+ 3323| type parameter | .. code-block:: typescript | 3324| | | 3325| | class A<T|null|undefined> {| 3326| | f: T | 3327| | m() { | 3328| | typeof this.f | 3329| | } | 3330| | constructor(p:T) { | 3331| | this.f = p | 3332| | } | 3333| | } | 3334+------------------------+-----------------------------+ 3335 3336.. index:: 3337 union type 3338 type parameter 3339 3340 3341| 3342 3343.. _Ensure-Not-Nullish Expressions: 3344 3345Ensure-Not-Nullish Expression 3346***************************** 3347 3348.. meta: 3349 frontend_status: Done 3350 3351*Ensure-not-nullish expression* is a postfix expression with the operator 3352'``!``'. An *ensure-not-nullish expression* in the expression *e!* checks 3353whether *e* of a nullish type (see :ref:`Nullish Types`) evaluates to a 3354nullish value. 3355 3356The syntax of *ensure-not-nullish expression* is presented below: 3357 3358.. code-block:: abnf 3359 3360 ensureNotNullishExpression: 3361 expression '!' 3362 ; 3363 3364If the expression *e* is not of a nullish type, then the operator '``!``' 3365has no effect. 3366 3367If the result of the evaluation of *e* is not equal to ``null`` or ``undefined``, 3368then the result of *e!* is the outcome of the evaluation of *e*. 3369 3370If the result of the evaluation of *e* is equal to ``null`` or ``undefined``, 3371then ``NullPointerError`` is thrown. 3372 3373Type of *ensure-not-nullish* expression is the non-nullish variant of 3374type of *e*. 3375 3376.. index:: 3377 ensure-not-nullish expression 3378 postfix expression 3379 prefix expression 3380 expression 3381 operator 3382 nullish type 3383 evaluation 3384 non-nullish variant 3385 nullish value 3386 null 3387 undefined 3388 3389| 3390 3391.. _Nullish-Coalescing Expression: 3392 3393Nullish-Coalescing Expression 3394***************************** 3395 3396.. meta: 3397 frontend_status: Done 3398 3399*Nullish-coalescing expression* is a binary expression that uses the operator 3400'``??``'. 3401 3402The syntax of *nullish-coalescing expression* is presented below: 3403 3404.. code-block:: abnf 3405 3406 nullishCoalescingExpression: 3407 expression '??' expression 3408 ; 3409 3410A *nullish-coalescing expression* checks whether the evaluation of the 3411left-hand-side expression equals the *nullish* value: 3412 3413- If so, then the right-hand-side expression evaluation is the result 3414 of a nullish-coalescing expression. 3415- If not so, then the result of the left-hand-side expression evaluation is 3416 the result of a nullish-coalescing expression, and the right-hand-side 3417 expression is not evaluated (the operator '``??``' is thus *lazy*). 3418 3419.. index:: 3420 nullish-coalescing expression 3421 binary expression 3422 operator 3423 evaluation 3424 expression 3425 nullish value 3426 lazy operator 3427 3428If the left-hand-side expression is not of a nullish type, then type of the 3429expression is a nullish-coalescing expression. Otherwise, type of a 3430nullish-coalescing expression is a normalized *union type* 3431(see :ref:`Union Types`) formed from the following: 3432 3433- Non-nullish variant of the type of the left-hand-side expression; and 3434- Type of the right-hand-side expression. 3435 3436The semantics of a nullish-coalescing expression is represented in the 3437following example: 3438 3439.. code-block:: typescript 3440 :linenos: 3441 3442 let x = expression1 ?? expression2 3443 3444 let x$ = expression1 3445 if (x$ == null) {x = expression2} else x = x$! 3446 3447 // Type of x is NonNullishType(expression1)|Type(expression2) 3448 3449A :index:`compile-time error` occurs if the nullish-coalescing operator is 3450mixed with conditional-and or conditional-or operators without parentheses. 3451 3452.. index:: 3453 nullish type 3454 nullish-coalescing expression 3455 union type 3456 non-nullish type 3457 expression 3458 nullish-coalescing operator 3459 conditional-and operator 3460 conditional-or operator 3461 3462| 3463 3464.. _Unary Expressions: 3465 3466Unary Expressions 3467***************** 3468 3469.. meta: 3470 frontend_status: Done 3471 3472The syntax of *unary expression* is presented below: 3473 3474.. code-block:: abnf 3475 3476 unaryExpression: 3477 expression '++' 3478 | expression '--' 3479 | '++' expression 3480 | '--' expression 3481 | '+' expression 3482 | '-' expression 3483 | '~' expression 3484 | '!' expression 3485 ; 3486 3487All expressions with unary operators (except postfix increment and postfix 3488decrement operators) group right-to-left for '``~+x``' to have the same meaning 3489as '``~(+x)``'. 3490 3491Type of any *unary Expression* is the type of the ``expression`` provided. 3492 3493.. index:: 3494 unary expression 3495 unary operator 3496 expression 3497 postfix 3498 postfix 3499 increment operator 3500 decrement operator 3501 3502.. _Postfix Increment: 3503 3504Postfix Increment 3505================= 3506 3507.. meta: 3508 frontend_status: Done 3509 3510*Postfix increment expression* is an *expression* followed by the increment 3511operator '``++``'. 3512 3513The *expression* must be *left-hand-side expression* 3514(see :ref:`Left-Hand-Side Expressions`), so it denotes a variable. 3515 3516A :index:`compile-time error` occurs if type of the 3517the *expression* is not convertible (see :ref:`Implicit Conversions`) to a 3518numeric type (see :ref:`Numeric Types`). 3519 3520Type of a *postfix increment expression* is the type of the variable. The 3521result of a *postfix increment expression* is a value, not a variable. 3522 3523If the evaluation of the operand *expression* completes normally at runtime, 3524then: 3525 3526- The value *1* is added to the value of the variable by using necessary 3527 conversions (see :ref:`Numeric Casting Conversions`); and 3528- The sum is stored back into the variable. 3529 3530.. index:: 3531 postfix 3532 increment expression 3533 increment operator 3534 expression 3535 conversion 3536 variable 3537 numeric type 3538 convertible expression 3539 value 3540 operand 3541 normal completion 3542 3543Otherwise, the *postfix increment expression* completes abruptly, and no 3544incrementation occurs. 3545 3546The value of the *postfix increment expression* is the value of the variable 3547*before* the new value is stored. 3548 3549.. index:: 3550 variable 3551 conversion 3552 numeric types conversion 3553 postfix 3554 increment expression 3555 abrupt completion 3556 expression 3557 variable 3558 postfix increment expression 3559 incrementation 3560 3561| 3562 3563.. _Postfix Decrement: 3564 3565Postfix Decrement 3566================= 3567 3568.. meta: 3569 frontend_status: Done 3570 todo: let a : Double = Double.Nan; a++; a--; ++a; --a; (assertion) 3571 3572*Postfix decrement expression* is an expression followed by the decrement 3573operator '``--``'. The expression must be *left-hand-side expression* (see 3574:ref:`Left-Hand-Side Expressions`). 3575 3576A :index:`compile-time error` occurs if type of the expression is not 3577convertible (see :ref:`Implicit Conversions`) to a numeric type (see 3578:ref:`Numeric Types`). 3579 3580Type of a postfix decrement expression is the type of the variable. The 3581result of a postfix decrement expression is a value, not a variable. 3582 3583If evaluation of the operand expression completes at runtime, then: 3584 3585.. index:: 3586 postfix 3587 decrement expression 3588 decrement operator 3589 variable 3590 expression 3591 conversion 3592 runtime 3593 operand 3594 completion 3595 evaluation 3596 3597- The value *1* is subtracted from the value of the variable by using 3598 necessary conversions (see :ref:`Numeric Casting Conversions`); and 3599- The sum is stored back into the variable. 3600 3601Otherwise, the *postfix decrement expression* completes abruptly, and 3602no decrementation occurs. 3603 3604The value of the *postfix decrement expression* is the value of the variable 3605*before* the new value is stored. 3606 3607.. index:: 3608 subtraction 3609 value 3610 variable 3611 conversion 3612 abrupt completion 3613 numeric types conversion 3614 abrupt completion 3615 decrementation 3616 decrement expression 3617 postfix 3618 variable 3619 value 3620 3621| 3622 3623.. _Prefix Increment: 3624 3625Prefix Increment 3626================ 3627 3628.. meta: 3629 frontend_status: Done 3630 3631*Prefix increment expression* is an expression preceded by the operator 3632'``++``'. The expression must be *left-hand-side expression* (see 3633:ref:`Left-Hand-Side Expressions`). 3634 3635A :index:`compile-time error` occurs if the type of 3636the expression is not convertible (see :ref:`Implicit Conversions`) to a 3637numeric type (see :ref:`Numeric Types`). 3638 3639Type of a prefix increment expression is the type of the variable. The 3640result of a prefix increment expression is a value, not a variable. 3641 3642If evaluation of the operand *expression* completes normally at runtime, then: 3643 3644.. index:: 3645 prefix 3646 increment operator 3647 increment expression 3648 expression 3649 variable 3650 expression 3651 normal completion 3652 conversion 3653 convertibility 3654 3655- The value *1* is added to the value of the variable by using necessary 3656 conversions (see :ref:`Numeric Casting Conversions`); and 3657- The sum is stored back into the variable. 3658 3659Otherwise, the *prefix increment expression* completes abruptly, and no 3660incrementation occurs. 3661 3662The value of the *prefix increment expression* is the value of the variable 3663*before* the new value is stored. 3664 3665.. index:: 3666 value 3667 variable 3668 conversion 3669 predefined type 3670 conversion 3671 abrupt completion 3672 prefix 3673 increment expression 3674 3675| 3676 3677.. _Prefix Decrement: 3678 3679Prefix Decrement 3680================ 3681 3682.. meta: 3683 frontend_status: Done 3684 3685*Prefix decrement expression* is an expression preceded by the operator 3686'``--``'. The expression must be *left-hand-side expression* (see 3687:ref:`Left-Hand-Side Expressions`). 3688 3689A :index:`compile-time error` occurs if type of the expression is not 3690convertible (see :ref:`Implicit Conversions`) to a numeric type (see 3691:ref:`Numeric Types`). 3692 3693Type of a prefix decrement expression is the type of the variable. The 3694result of a prefix decrement expression is a value, not a variable. 3695 3696.. index:: 3697 prefix 3698 decrement operator 3699 decrement expression 3700 expression 3701 operator 3702 variable 3703 expression 3704 value 3705 3706If evaluation of the operand *expression* completes normally at runtime, then: 3707 3708- The value *1* is subtracted from the value of the variable by using 3709 necessary conversions (see :ref:`Numeric Casting Conversions`); and 3710- The sum is stored back into the variable. 3711 3712Otherwise, the *prefix decrement expression* completes abruptly, and no 3713decrementation occurs. The value of the *prefix decrement expression* remains 3714the value of the variable *before* a new value is stored. 3715 3716.. index:: 3717 evaluation 3718 runtime 3719 expression 3720 normal completion 3721 conversion 3722 decrement expression 3723 decrementation 3724 abrupt completion 3725 variable 3726 value 3727 prefix 3728 3729| 3730 3731.. _Unary Plus: 3732 3733Unary Plus 3734========== 3735 3736.. meta: 3737 frontend_status: Done 3738 3739*Unary plus expression* is an expression preceded by the operator '``+``'. 3740Type of the operand expression with the unary operator '``+``' must 3741be convertible (see :ref:`Implicit Conversions`) to a numeric type (see 3742:ref:`Numeric Types`). Otherwise, a :index:`compile-time error` occurs. 3743 3744The numeric types conversion is 3745performed on the operand to ensure that the resultant type is that of the 3746unary plus expression. The result of a unary plus expression is always a value, 3747not a variable (even if the result of the operand expression is a variable). 3748 3749Type of the *unary plus expression* is the type of the expression provided. 3750 3751.. index:: 3752 unary plus operator 3753 operand 3754 expression 3755 unary operator 3756 conversion 3757 numeric type 3758 numeric types conversion 3759 unary plus 3760 operator 3761 value 3762 variable 3763 3764| 3765 3766.. _Unary Minus: 3767 3768Unary Minus 3769=========== 3770 3771.. meta: 3772 frontend_status: Done 3773 todo: let a : Double = Double.Nan; a = -a; (assertion) 3774 3775*Unary minus expression* is an expression preceded by the operator '``-``'. 3776Type of the operand expression with the unary operator '``-``' must 3777be convertible (see :ref:`Widening Numeric Conversions`) to a numeric type (see 3778:ref:`Numeric Types`). Otherwise, a :index:`compile-time error` occurs. 3779 3780The numeric types conversion 3781is performed on the operand to ensure that the resultant type is that of the 3782unary minus expression. 3783The result of a unary minus expression is a value, not a variable (even if the 3784result of the operand expression is a variable). 3785 3786The unary negation operation is always performed on, and the result is drawn 3787from the same value set as the promoted operand value. 3788 3789Type of the *unary minus expression* is the type of the expression provided. 3790 3791 3792.. index:: 3793 unary minus 3794 operand 3795 unary operator 3796 operator 3797 conversion 3798 convertibility 3799 numeric type 3800 numeric types conversion 3801 expression 3802 operand 3803 normal completion 3804 value 3805 variable 3806 unary numeric promotion 3807 value set conversion 3808 unary negation operation 3809 promoted operand value 3810 3811Further value set conversions are then performed on the same result. 3812 3813The value of a unary minus expression at runtime is the arithmetic negation 3814of the promoted value of the operand. 3815 3816The negation of integer values is the same as subtraction from zero. The |LANG| 3817programming language uses two’s-complement representation for integers. The 3818range of two’s-complement value is not symmetric. The same maximum negative 3819number results from the negation of the maximum negative *int* or *long*. 3820In that case, an overflow occurs but throws no error. For any integer value 3821*x*, *-x* is equal to *(~x)+1*. 3822 3823The negation of floating-point values is *not* the same as subtraction from 3824zero (if *x* is *+0.0*, then *0.0-x* is *+0.0*, however *-x* is *-0.0*). 3825 3826A unary minus merely inverts the sign of a floating-point number. Special 3827cases to consider are as follows: 3828 3829- Operand ``NaN`` results in ``NaN`` (``NaN`` has no sign). 3830- Operand infinity results in the infinity of the opposite sign. 3831- Operand zero results in zero of the opposite sign. 3832 3833.. index:: 3834 value set conversion 3835 conversion 3836 unary minus 3837 negation 3838 promoted value 3839 operand 3840 operation 3841 integer value 3842 subtraction 3843 two’s-complement representation 3844 two’s-complement value 3845 overflow 3846 floating-point value 3847 subtraction 3848 floating-point number 3849 infinity 3850 NaN 3851 3852| 3853 3854.. _Bitwise Complement: 3855 3856Bitwise Complement 3857================== 3858 3859.. meta: 3860 frontend_status: Done 3861 3862*Bitwise complement* operator '``~``' is applied to an operand 3863of a numeric type or type ``bigint``. 3864 3865If the type of the operand is ``double`` or ``float``, then it is truncated 3866first to the appropriate integer type. 3867If the type of the operand is ``byte`` or ``short``, then the operand is 3868converted to ``int``. 3869If the type of the operand is ``bigint``, then no conversion is required. 3870 3871The resultant type of this operator is the type of its operand. 3872 3873The result of a unary bitwise complement expression is a value, not a variable 3874(even if the result of the operand expression is a variable). 3875 3876The value of a unary bitwise complement expression at runtime is the bitwise 3877complement of the value of the operand. In all cases, *~x* equals 3878*(-x)-1*. 3879 3880.. index:: 3881 bitwise complement expression 3882 numeric type 3883 operator 3884 complement operator 3885 operand 3886 unary operator 3887 integer type 3888 unary bitwise complement expression 3889 variable 3890 runtime 3891 3892| 3893 3894.. _Logical Complement: 3895 3896Logical Complement 3897================== 3898 3899.. meta: 3900 frontend_status: Done 3901 3902*Logical complement expression* is an expression preceded by the operator 3903'``!``'. Type of the operand expression with the unary '``!``' operator must be 3904``boolean`` or type mentioned in :ref:`Extended Conditional Expressions`. 3905Otherwise, a :index:`compile-time error` occurs. 3906 3907The unary logical complement expression type is ``boolean``. 3908 3909The value of a unary logical complement expression is ``true`` if the (possibly 3910converted) operand value is ``false``, and ``false`` if the operand value 3911(possibly converted) is ``true``. 3912 3913.. index:: 3914 logical complement operator 3915 expression 3916 operand 3917 operand value 3918 operator 3919 unary operator 3920 boolean type 3921 compile-time error 3922 unary logical complement expression 3923 predefined numeric types conversion 3924 3925| 3926 3927.. _Multiplicative Expressions: 3928 3929Multiplicative Expressions 3930************************** 3931 3932.. meta: 3933 frontend_status: Done 3934 3935Multiplicative expressions use *multiplicative operators* '``*``', '``/``', 3936and '``%``'. 3937 3938The syntax of *multiplicative expression* is presented below: 3939 3940.. code-block:: abnf 3941 3942 multiplicativeExpression: 3943 expression '*' expression 3944 | expression '/' expression 3945 | expression '%' expression 3946 | expression '**' expression 3947 ; 3948 3949Multiplicative operators group left-to-right. 3950 3951Type of each operand in a multiplicative operator must be convertible (see 3952:ref:`Numeric Operator Contexts`) to a numeric type (see :ref:`Numeric Types`). 3953Otherwise, a :index:`compile-time error` occurs. 3954 3955The numeric types conversion (see :ref:`Widening Numeric Conversions`) 3956is performed on both operands to ensure that the resultant type is the type of 3957the multiplicative expression. 3958 3959The result of a unary bitwise complement expression is a value, not a 3960variable (even if the operand expression is a variable). 3961 3962.. index:: 3963 multiplicative expression 3964 conversion 3965 convertibility 3966 context 3967 conversion 3968 numeric type 3969 multiplicative operator 3970 multiplicative expression 3971 numeric type 3972 value 3973 unary bitwise complement expression 3974 operand expression 3975 variable 3976 numeric type 3977 numeric types conversion 3978 multiplicative operator 3979 operand expression 3980 3981| 3982 3983.. _Multiplication: 3984 3985Multiplication 3986============== 3987 3988.. meta: 3989 frontend_status: Done 3990 todo: If either operand is NaN, the result should be NaN, but result is -NaN 3991 todo: Multiplication of an infinity by a zero should be NaN, but result is - NaN 3992 3993The binary operator '``*``' performs multiplication, and returns the product of 3994its operands. 3995 3996Multiplication is a commutative operation if operand expressions have no 3997side effects. 3998 3999Integer multiplication is associative when all operands are of the same type. 4000 4001Floating-point multiplication is not associative. 4002 4003Type of a *multiplication expression* is the 'heaviest' (see 4004:ref:`Numeric Types`) type of its operands. 4005 4006If overflow occurs during integer multiplication, then: 4007 4008- The result is the low-order bits of the mathematical product as represented 4009 in some sufficiently large two’s-complement format. 4010- The sign of the result can be other than the sign of the mathematical 4011 product of the two operand values. 4012 4013A floating-point multiplication result is determined in compliance with the 4014IEEE 754 arithmetic: 4015 4016.. index:: 4017 multiplication 4018 binary operator 4019 multiplication 4020 operand 4021 commutative operation 4022 expression 4023 side effect 4024 integer multiplication 4025 associativity 4026 two’s-complement format 4027 floating-type multiplication 4028 operand value 4029 low-order bit 4030 IEEE 754 4031 overflow 4032 4033- The result is ``NaN`` if: 4034 4035 - Either operand is ``NaN``; 4036 - Infinity is multiplied by zero. 4037 4038- If the result is not ``NaN``, then the sign of the result is as follows: 4039 4040 - Positive, where both operands have the same sign; and 4041 - Negative, where the operands have different signs. 4042 4043- If infinity is multiplied by a finite value, then the multiplication results 4044 in a signed infinity (the sign is determined by the rule above). 4045- If neither ``NaN`` nor infinity is involved, then the exact mathematical 4046 product is computed. 4047 4048 The product is rounded to the nearest value in the chosen value set by 4049 using the IEEE 754 *round-to-nearest* mode. The |LANG| programming 4050 language requires gradual underflow support as defined by IEEE 754 4051 (see :ref:`Floating-Point Types and Operations`). 4052 4053 If the magnitude of the product is too large to represent, then the 4054 operation overflows, and the result is an appropriately signed infinity. 4055 4056The evaluation of a multiplication operator '``*``' never throws an error 4057despite possible overflow, underflow, or loss of information. 4058 4059.. index:: 4060 NaN 4061 infinity 4062 operand 4063 finite value 4064 multiplication 4065 signed infinity 4066 round-to-nearest 4067 rounding 4068 underflow 4069 floating-point type 4070 floating-point operation 4071 overflow 4072 evaluation 4073 multiplication operator 4074 error 4075 loss of information 4076 IEEE 754 4077 rounding 4078 4079| 4080 4081.. _Division: 4082 4083Division 4084======== 4085 4086.. meta: 4087 frontend_status: Done 4088 todo: If either operand is NaN, the result should be NaN, but result is -NaN 4089 todo: Division of infinity by infinity should be NaN, but result is - NaN 4090 todo: Division of a nonzero finite value by a zero results should be signed infinity, but "Floating point exception(core dumped)" occurs 4091 4092The binary operator '``/``' performs division and returns the quotient of its 4093left-hand-side and right-hand-side expressions (``dividend`` and ``divisor`` 4094respectively). 4095 4096Integer division rounds toward *0*, i.e., the quotient of integer operands 4097*n* and *d*, after a numeric types conversion on both (see 4098:ref:`Widening Numeric Conversions` for details), is 4099the integer value *q* with the largest possible magnitude that 4100satisfies :math:`|d\cdot{}q|\leq{}|n|`. 4101 4102**Note**. The integer value *q* is: 4103 4104- Positive, where \|n| :math:`\geq{}` \|d|, and *n* and *d* have the same sign; 4105 but 4106- Negative, where \|n| :math:`\geq{}` \|d|, and *n* and *d* have opposite signs. 4107 4108.. index:: 4109 division operator 4110 binary operator 4111 operand 4112 dividend 4113 divisor 4114 round-toward-zero 4115 integer division 4116 integer operand 4117 numeric types conversion 4118 numeric type 4119 integer value 4120 4121Only a single special case does not comply with this rule: the integer overflow 4122occurs, and the result equals the dividend if the dividend is a negative 4123integer of the largest possible magnitude for its type, while the divisor 4124is *-1*. No error is thrown in this case despite the overflow. However, if the 4125divisor value is *0* in an integer division, then ``ArithmeticError`` is 4126thrown. 4127 4128The result of a floating-point division is determined in compliance with the 4129IEEE 754 arithmetic: 4130 4131- The result is ``NaN`` if: 4132 4133 - Either operand is NaN; 4134 - Both operands are infinity; or 4135 - Both operands are zero. 4136 4137.. index:: 4138 integer overflow 4139 dividend 4140 negative integer 4141 floating-point division 4142 divisor 4143 overflow 4144 integer division 4145 floating-point division 4146 NaN 4147 infinity 4148 operand 4149 IEEE 754 4150 4151- If the result is not ``NaN``, then the sign of the result is: 4152 4153 - Positive, where both operands have the same sign; or 4154 - Negative, where the operands have different signs. 4155 4156- Division produces a signed infinity (the sign is determined by 4157 the rule above) if: 4158 4159 - Infinity is divided by a finite value; and 4160 - A nonzero finite value is divided by zero. 4161 4162- Division produces a signed zero (the sign is determined by the 4163 rule above) if: 4164 4165 - A finite value is divided by infinity; and 4166 - Zero is divided by any other finite value. 4167 4168.. index:: 4169 NaN 4170 operand 4171 division 4172 signed infinity 4173 finite value 4174 4175- If neither ``NaN`` nor infinity is involved, then the exact mathematical 4176 quotient is computed. 4177 4178 If the magnitude of the product is too large to represent, then the 4179 operation overflows, and the result is an appropriately signed infinity. 4180 4181The quotient is rounded to the nearest value in the chosen value set by 4182using the IEEE 754 *round-to-nearest* mode. The |LANG| programming 4183language requires gradual underflow support as defined by IEEE 754 (see 4184:ref:`Floating-Point Types and Operations`). 4185 4186The evaluation of a floating-point division operator '``/``' never throws an 4187error despite possible overflow, underflow, division by zero, or loss of 4188information. 4189 4190The type of the *division expression* is the '*heaviest*' numeric type (see 4191:ref:`Numeric Types`) of its operands. 4192 4193 4194.. index:: 4195 infinity 4196 NaN 4197 overflow 4198 floating-point division 4199 round-to-nearest 4200 rounding 4201 underflow 4202 floating-point type 4203 floating-point operation 4204 loss of information 4205 division 4206 division operator 4207 IEEE 754 4208 4209 4210| 4211 4212.. _Remainder: 4213 4214Remainder 4215========= 4216 4217.. meta: 4218 frontend_status: Done 4219 todo: If either operand is NaN, the result should be NaN, but result is -NaN 4220 todo: if the dividend is an infinity, or the divisor is a zero, or both, the result should be NaN, but this is -NaN 4221 4222The binary operator '``%``' yields the remainder of its operands (``dividend`` 4223as the left-hand-side, and ``divisor`` as the right-hand-side operand) from an 4224implied division. 4225 4226The remainder operator in |LANG| accepts floating-point operands (unlike in 4227C and C++). 4228 4229The remainder operation on integer operands produces a result value, i.e., 4230:math:`(a/b)*b+(a\%b)` equals *a*. The numeric type conversion on remainder 4231operation is discussed in :ref:`Widening Numeric Conversions`. 4232 4233.. index:: 4234 binary operator 4235 remainder operator 4236 dividend 4237 divisor 4238 division 4239 numeric types conversion 4240 conversion 4241 floating-point operand 4242 remainder operation 4243 value 4244 integer operand 4245 numeric type 4246 4247This equality holds even in the special case where the dividend is a negative 4248integer of the largest possible magnitude of its type, and the divisor is *-1* 4249(the remainder is then *0*). According to this rule, the result of the remainder 4250operation can only be one of the following: 4251 4252- Negative if the dividend is negative; or 4253- Positive if the dividend is positive. 4254 4255The magnitude of the result is always less than that of the divisor. 4256 4257If the value of the divisor for an integer remainder operator is *0*, then 4258``ArithmeticError`` is thrown. 4259 4260The result of a floating-point remainder operation as computed by the operator 4261'``%``' is different than that produced by the remainder operation defined by 4262IEEE 754. The IEEE 754 remainder operation computes the remainder from a rounding 4263division (not a truncating division), and its behavior is different from that 4264of the usual integer remainder operator. On the contrary, |LANG| presumes that 4265the operator '``%``' behaves on floating-point operations in the same manner as 4266the integer remainder operator (comparable to the C library function *fmod*). 4267The standard library (see :ref:`Standard Library`) routine ``Math.IEEEremainder`` 4268can compute the IEEE 754 remainder operation. 4269 4270.. index:: 4271 dividend 4272 equality 4273 magnitude 4274 negative integer 4275 divisor 4276 remainder operator 4277 remainder operation 4278 truncation 4279 integer remainder 4280 value 4281 floating-point remainder operation 4282 floating-point operation 4283 division 4284 truncation 4285 rounding 4286 routine 4287 IEEE 754 4288 4289The result of a floating-point remainder operation is determined in compliance 4290with the IEEE 754 arithmetic: 4291 4292- The result is ``NaN`` if: 4293 4294 - Either operand is ``NaN``; 4295 - The dividend is infinity; 4296 - The divisor is zero; or 4297 - The dividend is infinity, and the divisor is zero. 4298 4299- If the result is not ``NaN``, then the sign of the result is the same as the 4300 sign of the dividend. 4301- The result equals the dividend if: 4302 4303 - The dividend is finite, and the divisor is infinity; or 4304 - If the dividend is zero, and the divisor is finite. 4305 4306.. index:: 4307 floating-point remainder operation 4308 remainder operation 4309 NaN 4310 infinity 4311 divisor 4312 dividend 4313 IEEE 754 4314 4315- If infinity, zero, or ``NaN`` are not involved, then the floating-point remainder 4316 *r* from the division of the dividend *n* by the divisor *d* is determined 4317 by the mathematical relation :math:`r=n-(d\cdot{}q)`, where *q* is an 4318 integer that is only: 4319 4320 - Negative if :math:`n/d` is negative, or 4321 - Positive if :math:`n/d` is positive. 4322 4323- The magnitude of *q* is the largest possible without exceeding the 4324 magnitude of the true mathematical quotient of *n* and *d*. 4325 4326The evaluation of the floating-point remainder operator '``%``' never throws 4327an error, even if the right-hand operand is zero. Overflow, underflow, or 4328loss of precision cannot occur. 4329 4330The type of the *remainder expression* is the '*heaviest*' numeric type (see 4331:ref:`Numeric Types`) of its operands. 4332 4333 4334.. index:: 4335 infinity 4336 NaN 4337 floating-point remainder 4338 remainder operator 4339 dividend 4340 integer 4341 loss of precision 4342 operand 4343 magnitude 4344 underflow 4345 error 4346 overflow 4347 loss of precision 4348 4349| 4350 4351.. _Exponentiation: 4352 4353Exponentiation 4354============== 4355 4356.. meta: 4357 frontend_status: None 4358 4359The binary operator '``**``' yields the result of raising the first operand 4360(base) to the power of the second operand (exponent). The operation returns 4361NaN in the following cases: 4362 4363- Exponent is NaN; 4364- Base is NaN, and exponent is not 0; 4365- Base is ±1, and exponent is ±Infinity; or 4366- Base is less than 0, and exponent is not an integer. 4367 4368The binary operator '``**``' is equivalent to Math.pow(), except it also 4369accepts BigInts as operands. 4370 4371 4372| 4373 4374.. _Additive Expressions: 4375 4376Additive Expressions 4377******************** 4378 4379.. meta: 4380 frontend_status: Done 4381 4382Additive expressions use *additive operators* '``+``' and '``-``'. 4383 4384The syntax of *additive expression* is presented below: 4385 4386 4387.. code-block:: abnf 4388 4389 additiveExpression: 4390 expression '+' expression 4391 | expression '-' expression 4392 ; 4393 4394Additive operators group left-to-right. 4395 4396If either operand of the operator is '``+``' of type ``string``, then the 4397operation is a string concatenation (see :ref:`String Concatenation`). In all 4398other cases, type of each operand of the operator '``+``' must be 4399convertible (see :ref:`Widening Numeric Conversions`) to a numeric type (see 4400:ref:`Numeric Types`). Otherwise, a :index:`compile-time error` occurs. 4401 4402Type of each operand of the binary operator '``-``' must be convertible 4403(see :ref:`Widening Numeric Conversions`) to a numeric type (see 4404:ref:`Numeric Types`) in all cases. Otherwise, a :index:`compile-time error` 4405occurs. 4406 4407Type of *Additive expression* is ``string`` or the 'heaviest' (see 4408:ref:`Numeric Types`) type of its operands. 4409 4410 4411.. index:: 4412 additive expression 4413 additive operator 4414 operand 4415 string 4416 string concatenation 4417 operator 4418 conversion 4419 numeric type 4420 binary operator 4421 4422| 4423 4424.. _String Concatenation: 4425 4426String Concatenation 4427==================== 4428 4429.. meta: 4430 frontend_status: Done 4431 4432If one operand of an expression is of type ``string``, then the string 4433conversion (see :ref:`String Operator Contexts`) is performed on the other 4434operand at runtime to produce a string. 4435 4436String concatenation produces a reference to a ``string`` object that is a 4437concatenation of two operand strings. The left-hand-side operand characters 4438precede the right-hand-side operand characters in a newly created string. 4439 4440If the expression is not a constant expression (see :ref:`Constant Expressions`), 4441then a new ``string`` object is created (see :ref:`New Expressions`). 4442 4443.. index:: 4444 string concatenation 4445 string 4446 operand 4447 string conversion 4448 operator context 4449 runtime 4450 operand string 4451 expression 4452 constant expression 4453 object 4454 4455| 4456 4457.. _Additive Operators for Numeric Types: 4458 4459Additive Operators for Numeric Types 4460==================================== 4461 4462.. meta: 4463 frontend_status: Done 4464 todo: The sum of two infinities of opposite sign should be NaN, but it is -NaN 4465 4466The numeric types conversion (see :ref:`Widening Numeric Conversions`) 4467performed on a pair of operands ensures that both operands are of a numeric 4468type. If the conversion fails, then a :index:`compile-time error` occurs. 4469 4470The binary operator '``+``' performs addition and produces the sum of such 4471operands. 4472 4473The binary operator '``-``' performs subtraction and produces the difference 4474of two numeric operands. 4475 4476Type of an additive expression performed on numeric operands is the 4477largest type (see :ref:`Numeric Types`) to which operands of that 4478expression are converted. 4479 4480If the promoted type is ``int`` or ``long``, then integer arithmetic is 4481performed. 4482If the promoted type is ``float`` or ``double``, then floating-point arithmetic 4483is performed. 4484 4485.. index:: 4486 additive operator 4487 conversion 4488 numeric type 4489 numeric operand 4490 binary operator 4491 promoted type 4492 integer arithmetic 4493 floating-point arithmetic 4494 integer 4495 type operand 4496 addition 4497 subtraction 4498 expression 4499 4500If operand expressions have no side effects, then addition is a commutative 4501operation. 4502 4503If all operands are of the same type, then integer addition is associative. 4504 4505Floating-point addition is not associative. 4506 4507If overflow occurs on an integer addition, then: 4508 4509- Result is the low-order bits of the mathematical sum as represented in 4510 a sufficiently large two’s-complement format. 4511- Sign of the result is different than that of the mathematical sum of 4512 the operands’ values. 4513 4514The result of a floating-point addition is determined in compliance with the 4515IEEE 754 arithmetic as follows: 4516 4517.. index:: 4518 operand expression 4519 expression 4520 side effect 4521 addition 4522 commutative operation 4523 operation 4524 low-order bit 4525 two’s-complement format 4526 operand value 4527 overflow 4528 floating-point addition 4529 associativity 4530 IEEE 754 4531 4532- The result is ``NaN`` if: 4533 4534 - Either operand is ``NaN``; or 4535 - The operands are two infinities of the opposite signs. 4536 4537- The sum of two infinities of the same sign is the infinity of that sign. 4538- The sum of infinity and a finite value equals the infinite operand. 4539- The sum of two zeros of opposite sign is positive zero. 4540- The sum of two zeros of the same sign is zero of that sign. 4541- The sum of zero and a nonzero finite value is equal to the nonzero operand. 4542- The sum of two nonzero finite values of the same magnitude and opposite sign 4543 is positive zero. 4544- If infinity, zero, or ``NaN`` are not involved, and the operands have the 4545 same sign or different magnitudes, then the exact sum is computed 4546 mathematically. 4547 4548If the magnitude of the sum is too large to represent, then the operation 4549overflows. The result is an appropriately signed infinity. 4550 4551.. index:: 4552 NaN 4553 infinity 4554 signed infinity 4555 magnitude 4556 operand 4557 infinite operand 4558 infinite value 4559 nonzero operand 4560 finite value 4561 positive zero 4562 negative zero 4563 overflow 4564 operation overflow 4565 4566Otherwise, the sum is rounded to the nearest value within the chosen value set 4567by using the IEEE 754 *round-to-nearest* mode. The |LANG| programming language 4568requires gradual underflow support as defined by IEEE 754 (see 4569:ref:`Floating-Point Types and Operations`). 4570 4571When applied to two numeric type operands (see :ref:`Numeric Types`), the 4572binary operator '``-``' performs subtraction, and returns the difference of 4573such operands (``minuend`` as left-hand-side, and ``subtrahend`` as the 4574right-hand-side operand). 4575 4576The result of *a-b* is always the same as that of *a+(-b)* in both integer and 4577floating-point subtraction. 4578 4579The subtraction from zero for integer values is the same as negation. However, 4580the subtraction from zero for floating-point operands and negation is *not* 4581the same (if *x* is *+0.0*, then *0.0-x* is *+0.0*; however *-x* is *-0.0*). 4582 4583The evaluation of a numeric additive operator never throws an error despite 4584possible overflow, underflow, or loss of information. 4585 4586.. index:: 4587 round-to-nearest mode 4588 rounding 4589 value set 4590 underflow 4591 floating-point type 4592 floating-point operation 4593 floating-point subtraction 4594 floating-point operand 4595 subtraction 4596 integer subtraction 4597 integer value 4598 loss of information 4599 numeric type operand 4600 binary operator 4601 subtraction 4602 negation 4603 overflow 4604 additive operator 4605 error 4606 IEEE 754 4607 4608| 4609 4610.. _Shift Expressions: 4611 4612Shift Expressions 4613***************** 4614 4615.. meta: 4616 frontend_status: Done 4617 todo: spec issue: uses 'L' postfix in example "(n >> s) + (2L << ~s)", we don't have it 4618 4619*Shift expressions* use *shift operators* '``<<``' (left shift), '``>>``' 4620(signed right shift), and '``>>>``' (unsigned right shift). The value to be 4621shifted is the left-hand-side operand in a shift operator, and the 4622right-hand-side operand specifies the shift distance. 4623 4624The syntax of *shift expression* is presented below: 4625 4626.. code-block:: abnf 4627 4628 shiftExpression: 4629 expression '<<' expression 4630 | expression '>>' expression 4631 | expression '>>>' expression 4632 ; 4633 4634Shift operators group left-to-right. 4635 4636Both operands of a *shift expression* must be of numeric types 4637or type ``bigint``. 4638 4639If the type of one or both operands is ``double`` or ``float``, then the 4640operand or operands are truncated first to the appropriate integer type. 4641If the type of the left-hand-side operand is ``byte`` or ``short``, then the 4642operand is converted to ``int``. 4643If both operands are of type ``bigint``, then no conversion is required. 4644A :index:`compile-time error` occurs if one operand is type ``bigint``, and the 4645other one is a numeric type. 4646 4647The result of a *shift expression* is of the type to which its first operand 4648converted. 4649 4650.. index:: 4651 shift 4652 shift expression 4653 shift distance 4654 shift operator 4655 signed right shift 4656 unsigned right shift 4657 operand 4658 shift distance 4659 numeric type 4660 truncation 4661 integer type 4662 bigint 4663 4664If the left-hand-side operand is of the promoted type ``int``, then only five 4665lowest-order bits of the right-hand-side operand specify the shift distance 4666(as if using a bitwise logical AND operator '``&``' with the mask value *0x1f* 4667or *0b11111* on the right-hand-side operand). Thus, it is always within the 4668inclusive range of *0* through *31*. 4669 4670If the left-hand-side operand is of the promoted type ``long``, then only six 4671lowest-order bits of the right-hand-side operand specify the shift distance 4672(as if using a bitwise logical AND operator '``&``' with the mask value *0x3f* 4673or *0b111111* the right-hand-side operand). Thus, it is always within the 4674inclusive range of *0* through *63*. 4675 4676Shift operations are performed on the two’s-complement integer 4677representation of the value of the left-hand-side operand at runtime. 4678 4679The value of *n* ``<<`` *s* is *n* left-shifted by *s* bit positions. It is 4680equivalent to multiplication by two to the power *s* even in case of an 4681overflow. 4682 4683.. index:: 4684 shift expression 4685 promoted type 4686 operand 4687 shift distance 4688 bitwise logical AND operator 4689 mask value 4690 value 4691 truncation 4692 integer division 4693 shift operation 4694 multiplication 4695 overflow 4696 two’s-complement integer 4697 left shift 4698 runtime 4699 zero-extension 4700 shift 4701 4702The value of *n* ``>>`` *s* is *n* right-shifted by *s* bit positions with 4703sign-extension. The resultant value is :math:`floor(n / 2s)`. If *n* is 4704non-negative, then it is equivalent to truncating integer division (as computed 4705by the integer division operator by 2 to the power *s*). 4706 4707The value of *n* ``>>>`` *s* is *n* right-shifted by *s* bit positions with 4708zero-extension, where: 4709 4710- If *n* is positive, then the result is the same as that of *n* ``>>`` *s*. 4711- If *n* is negative, and type of the left-hand-side operand is ``int``, 4712 then the result is equal to that of the expression 4713 (*n* ``>>`` *s*) ``+ (2 << ~`` *s*). 4714- If *n* is negative, and type of the left-hand-side operand is ``long``, 4715 then the result is equal to that of the expression 4716 (*n* ``>>`` *s*) ``+ ((2 as long) << ~`` *s*). 4717 4718.. index:: 4719 value 4720 sign-extension 4721 right shift 4722 truncation 4723 integer division 4724 operator 4725 zero-extension 4726 operand 4727 expression 4728 4729| 4730 4731.. _Relational Expressions: 4732 4733Relational Expressions 4734********************** 4735 4736.. meta: 4737 frontend_status: Done 4738 todo: if either operand is NaN, then the result should be false, but Double.NaN < 2 is true, and assertion fail occurs with opt-level 2. (also fails with INF) 4739 todo: Double.POSITIVE_INFINITY > 1 should be true, but false (also fails with opt-level 2) 4740 4741Relational expressions use *relational operators* '``<``', '``>``', '``<=``', 4742and '``>=``'. 4743 4744The syntax of *relational expression* is presented below: 4745 4746.. code-block:: abnf 4747 4748 relationalExpression: 4749 expression '<' expression 4750 | expression '>' expression 4751 | expression '<=' expression 4752 | expression '>=' expression 4753 ; 4754 4755Relational operators group left-to-right. 4756 4757A relational expression is always of type ``boolean``. 4758 4759The four kinds of relational expressions are described below. The kind of a 4760relational expression depends on types of operands. It is a 4761:index:`compile-time error` if at least one type of operands is different from 4762types described below. 4763 4764.. index:: 4765 numerical relational operator 4766 relational operator 4767 relational expression 4768 boolean type 4769 expression 4770 operand 4771 type 4772 4773| 4774 4775.. _Numerical Relational Operators: 4776 4777Numerical Relational Operators 4778============================== 4779 4780.. meta: 4781 frontend_status: Done 4782 4783Type of each operand in a numerical relational operator must be convertible 4784to a numeric type (see :ref:`Numeric Types`) or to ``bigint`` type. 4785Otherwise, a :index:`compile-time error` occurs. 4786 4787Numeric types conversions (see :ref:`Widening Numeric Conversions`) are 4788performed on each operand. If at least one operand is of ``bigint`` type, then 4789the other operand is converted to ``bigint`` by using a ``BigInt()`` function. 4790 4791Depending on the heaviest type of operands, a comparison is performed as follows: 4792 4793- Signed integer comparison, if the converted type of the operand is ``int`` 4794 or ``long``. 4795 4796- Floating-point comparison, if the converted type of the operand is ``float`` 4797 or ``double``. 4798 4799- Bigint comparison, if the converted type of the operand is ``bigint``. 4800 4801 4802.. index:: 4803 numerical relational operator 4804 operand 4805 conversion 4806 numeric type 4807 numeric types conversion 4808 predefined numeric types conversion 4809 bigint 4810 signed integer comparison 4811 floating-point comparison 4812 bigint comparison 4813 converted type 4814 4815The comparison of floating-point values drawn from any value set must be accurate. 4816 4817A floating-point comparison must be performed in accordance with the IEEE 754 4818standard specification as follows: 4819 4820- The result of a floating-point comparison is false if either operand is ``NaN``. 4821 4822- All values other than ``NaN`` must be ordered with the following: 4823 4824 - Negative infinity less than all finite values; and 4825 - Positive infinity greater than all finite values. 4826 4827- Positive zero equals negative zero. 4828 4829.. index:: 4830 floating-point value 4831 floating-point comparison 4832 comparison 4833 NaN 4834 finite value 4835 infinity 4836 negative infinity 4837 positive infinity 4838 positive zero 4839 negative zero 4840 IEEE 754 4841 4842Based on the above presumption, the following rules apply to integer, 4843floating-point, or bigint operands other than ``NaN``: 4844 4845- The value produced by the operator '``<``' is ``true`` if the value of the 4846 left-hand-side operand is less than that of the right-hand-side operand. 4847 Otherwise, the value is ``false``. 4848- The value produced by the operator '``<=``' is ``true`` if the value of the 4849 left-hand-side operand is less than or equal to that of the right-hand-side 4850 operand. Otherwise, the value is ``false``. 4851- The value produced by the operator '``>``' is ``true`` if the value of the 4852 left-hand-side operand is greater than that of the right-hand-side operand. 4853 Otherwise, the value is ``false``. 4854- The value produced by the operator '``>=``' is ``true`` if the value of the 4855 left-hand-side operand is greater than or equal to that of the right-hand-side 4856 operand. Otherwise, the value is ``false``. 4857 4858.. index:: 4859 integer operand 4860 floating-point operand 4861 NaN 4862 operator 4863 value 4864 4865| 4866 4867.. _String Relational Operators: 4868 4869String Relational Operators 4870=========================== 4871 4872.. meta: 4873 frontend_status: Done 4874 4875Results of all string comparisons are defined as follows: 4876 4877- Operator '``<``' delivers ``true`` if the string value of the left-hand-side 4878 operand is lexicographically less than the string value of the right-hand-side 4879 operand, or ``false`` otherwise. 4880- Operator '``<=``' delivers ``true`` if the string value of the left-hand-side 4881 operand is lexicographically less than or equal to the string value of the 4882 right-hand-side operand, or ``false`` otherwise. 4883- Operator '``>``' delivers ``true`` if the string value of the left-hand-side 4884 operand is lexicographically greater than the string value of the 4885 right-hand-side operand, or ``false`` otherwise. 4886- Operator '``>=``' delivers ``true`` if the string value of the left-hand-side 4887 operand is lexicographically greater than or equal to the string value of 4888 the right-hand operand, or ``false`` otherwise. 4889 4890.. index:: 4891 operator 4892 string comparison 4893 string value 4894 4895| 4896 4897.. _Boolean Relational Operators: 4898 4899Boolean Relational Operators 4900============================ 4901 4902.. meta: 4903 frontend_status: Done 4904 4905Results of all boolean comparisons are defined as follows: 4906 4907- Operator '``<``' delivers ``true`` if the left-hand-side operand is ``false`` 4908 and the right-hand-side operand is true, or ``false`` otherwise. 4909- Operator '``<=``' delivers ``true`` if the left-hand-side operand is ``false`` 4910 and the right-hand-side operand is ``true`` or ``false``, or ``false`` otherwise. 4911- Operator '``>``' delivers ``true`` if the left-hand-side operand is ``true`` 4912 and the right-hand-side operand is ``false``, or ``false`` otherwise. 4913- Operator '``>=``' delivers ``true`` if the left-hand-side operand is ``true`` 4914 and the right-hand-side operand is ``false`` or ``true``, or ``false`` otherwise. 4915 4916.. index:: 4917 operator 4918 operand 4919 relational operator 4920 boolean comparison 4921 4922| 4923 4924.. _Enumeration Relational Operators: 4925 4926Enumeration Relational Operators 4927================================ 4928 4929.. meta: 4930 frontend_status: Done 4931 4932If both operands are of the same Enumeration type (see :ref:`Enumerations`), 4933then :ref:`Numerical Relational Operators` or :ref:`String Relational Operators` 4934are used depending on the kind of enumeration constant value 4935( :ref:`Enumeration Integer Values` or :ref:`Enumeration String Values`). 4936Otherwise, a :index:`compile-time error` occurs. 4937 4938.. index:: 4939 enumeration operator 4940 enumeration constant 4941 value 4942 string value 4943 relational operator 4944 boolean comparison 4945 constant value 4946 4947| 4948 4949.. _Equality Expressions: 4950 4951Equality Expressions 4952******************** 4953 4954.. meta: 4955 frontend_status: Done 4956 4957Equality expressions use *equality operators* '``==``', '``===``', '``!=``', 4958and '``!==``'. 4959 4960The syntax of *equality expression* is presented below: 4961 4962.. code-block:: abnf 4963 4964 equalityExpression: 4965 expression ('==' | '===' | '!=' | '!==') expression 4966 ; 4967 4968Any equality expression is of type ``boolean``. The result of operators '``==``' 4969and '``===``' is ``true`` if operands are *equal* as shown below. Otherwise, the 4970result is ``false``. 4971 4972Equality operators group left-to-right. 4973Equality operators are commutative if operand expressions cause no side 4974effects. 4975 4976Equality operators are similar to relational operators, except for their 4977lower precedence (:math:`a < b==c < d` is ``true`` if both :math:`a < b` 4978and :math:`c < d` have the same ``truth`` value). 4979 4980.. index:: 4981 equality operator 4982 equality expression 4983 boolean type 4984 relational operator 4985 4986In all cases, ``a != b`` produces the same result as ``!(a == b)``, and 4987``a !== b`` produces the same result as ``!(a === b)``. 4988 4989The result of operators '``==``' and '``===``' is the same in all cases, 4990except when comparing the values ``null`` and ``undefined`` (see 4991:ref:`Reference Equality`). 4992 4993The variant of equality evaluation to be used depends on types of the 4994operands used as follows: 4995 4996- *Value equality* is applied to entities of :ref:`Value Types`, 4997 type ``string`` (see :ref:`Type string`) and type ``bigint`` (see 4998 :ref:`Type bigint`). 4999- *Reference Equality based on actual (dynamic) type* is applied to values of 5000 type ``Object`` (:ref:`Type Object`), values of union types 5001 (:ref:`Union Types`), type parameters (:ref:`Type Parameters`), and if at 5002 least one type is of interface type (:ref:`Interfaces`). 5003- *Reference equality* is applied to entities of all other reference types 5004 (see :ref:`Reference Types`). 5005 5006.. index:: 5007 operator 5008 value 5009 value equality 5010 primitive type 5011 value type 5012 enumeration type 5013 bigint 5014 reference equality 5015 object 5016 type parameter 5017 5018Operators '``===``' and '``==``', or '``!==``' and '``!=``' are used for: 5019 5020- :ref:`Numerical Equality Operators` if both operands are 5021 of :ref:`Numeric Types`); 5022 5023- :ref:`String Equality Operators` if both operands are of type ``string``; 5024 5025- :ref:`Bigint Equality Operators` if both operands are of type ``bigint``; 5026 5027- :ref:`Boolean Equality Operators` if both operands are of type ``boolean``; 5028 5029- :ref:`Character Equality Operators` if both operands are of type ``char``; 5030 5031- :ref:`Enumeration Equality Operators` if both operands are of an enumeration 5032 type; 5033 5034- :ref:`Function type Equality Operators` if both operands are of a function 5035 type; 5036 5037- :ref:`Reference Equality based on actual type` if at least one operand is of 5038 ``Object`` type, union type, interface type, or is a type parameter; 5039 5040- :ref:`Reference Equality` if both operands are of compatible reference types, 5041 except types ``string``, ``bigint``, ``Object``, union types, and type 5042 parameters; 5043 5044- :ref:`Extended Equality with null or undefined` if one operand is ``null`` or 5045 ``undefined``. 5046 5047- Otherwise, a :index:`compile-time error` occurs. 5048 5049.. code-block:: typescript 5050 :linenos: 5051 5052 // Entities of value types are not comparable between each other 5053 5 == "5" // compile-time error 5054 5 == true // compile-time error 5055 "5" == true // compile-time error 5056 5057.. index:: 5058 value equality 5059 comparison 5060 operand 5061 operator 5062 numerical equality 5063 enumeration 5064 equality operator 5065 numeric type 5066 string 5067 equality operator 5068 boolean type 5069 type parameter 5070 object 5071 reference type 5072 union type 5073 type parameter 5074 5075| 5076 5077.. _Numerical Equality Operators: 5078 5079Numerical Equality Operators 5080============================ 5081 5082.. meta: 5083 frontend_status: Done 5084 5085Type of each operand in a numerical equality operator must be convertible 5086(see :ref:`Implicit Conversions`) to a numeric type (see :ref:`Numeric Types`). 5087Otherwise, a :index:`compile-time error` occurs. 5088 5089A widening conversion can occur (see :ref:`Widening Numeric Conversions`) 5090if type of one operand is smaller than type of the other operand (see 5091:ref:`Numeric Types`). 5092 5093If the converted type of the operands is ``int`` or ``long``, then an 5094integer equality test is performed. 5095 5096If the converted type is ``float`` or ``double``, then a floating-point 5097equality test is performed. 5098 5099The floating-point equality test must be performed in accordance with the 5100following IEEE 754 standard rules: 5101 5102.. index:: 5103 numerical equality 5104 value equality 5105 operator 5106 numeric type 5107 numeric types conversion 5108 converted type 5109 floating-point equality test 5110 operand 5111 conversion 5112 integer equality test 5113 IEEE 754 5114 widening 5115 primitive conversion 5116 5117- The result of '``==``' or '``===``' is ``false`` but the result of '``!=``' 5118 is ``true`` if either operand is ``NaN``. 5119 5120 The test ``x != x`` or ``x !== x`` is ``true`` only if *x* is ``NaN``. 5121 5122- Positive zero equals negative zero. 5123 5124- Equality operators consider two distinct floating-point values unequal 5125 in any other situation. 5126 5127 For example, if one value represents positive infinity, and the other 5128 represents negative infinity, then each compares equal to itself and 5129 unequal to all other values. 5130 5131Based on the above presumptions, the following rules apply to integer operands 5132or floating-point operands other than ``NaN``: 5133 5134- If the value of the left-hand-side operand is equal to that of the 5135 right-hand-side operand, then the operator '``==``' or '``===``' produces 5136 the value ``true``. Otherwise, the result is ``false``. 5137 5138- If the value of the left-hand-side operand is not equal to that of the 5139 right-hand-side operand, then the operator '``!=``' or '``!==``' produces 5140 the value ``true``. Otherwise, the result is ``false``. 5141 5142The following example illustrates *numerical equality*: 5143 5144.. code-block:: typescript 5145 :linenos: 5146 5147 5 == 5 // true 5148 5 != 5 // false 5149 5150 5 === 5 // true 5151 5152 5 == new Number(5) // true 5153 5 === new Number(5) // true 5154 5155 5 == 5.0 // true 5156 5157.. index:: 5158 NaN 5159 value equality 5160 floating-point value 5161 floating-point operand 5162 numerical equality 5163 positive infinity 5164 negative infinity 5165 positive zero 5166 negative zero 5167 equality operator 5168 integer operand 5169 5170| 5171 5172.. _String Equality Operators: 5173 5174String Equality Operators 5175========================= 5176 5177.. meta: 5178 frontend_status: Done 5179 5180Type of one operand must be of type ``string``, other operand must 5181be convertible (see :ref:`Implicit Conversions`) to ``string`` type. 5182 5183Two strings are equal if they represent the same sequence of characters: 5184 5185.. code-block:: typescript 5186 :linenos: 5187 5188 "abc" == "abc" // true 5189 "abc" === "ab" + "c" // true 5190 5191 function foo(s: string) { 5192 console.log(s == "hello") 5193 } 5194 foo("hello") // prints "true" 5195 5196.. index:: 5197 value equality 5198 string 5199 string equality operator 5200 operand 5201 convertibility 5202 5203| 5204 5205.. _Bigint Equality Operators: 5206 5207Bigint Equality Operators 5208========================== 5209 5210.. meta: 5211 frontend_status: Done 5212 5213*Bigint equality* is used for operands of type ``bigint``. 5214 5215Two ``bigints`` are equal if they have the same value: 5216 5217.. code-block:: typescript 5218 :linenos: 5219 5220 let x = 2n 5221 x == 2n // true 5222 5223.. index:: 5224 value equality 5225 bigint equality operator 5226 bigint 5227 equality operator 5228 boolean equality 5229 operand 5230 value 5231 5232| 5233 5234.. _Boolean Equality Operators: 5235 5236Boolean Equality Operators 5237========================== 5238 5239.. meta: 5240 frontend_status: Done 5241 5242*Boolean equality* is used for operands of type ``boolean``. 5243 5244If both operands are 5245either ``true`` or ``false``, then the result of ':math:`==`' or ':math:`===`' 5246is ``true``. Otherwise, the result is ``false``. 5247 5248If both operands are either ``true`` or ``false``, then the result of '``!=``' 5249or '``!==``' is ``false``. Otherwise, the result is ``true``. 5250 5251.. index:: 5252 value equality 5253 boolean type 5254 boolean equality 5255 boolean equality operator 5256 equality operator 5257 value equality operator 5258 operand 5259 5260| 5261 5262.. _Enumeration Equality Operators: 5263 5264Enumeration Equality Operators 5265============================== 5266 5267.. meta: 5268 frontend_status: Done 5269 5270If both operands are of the same enumeration type (see :ref:`Enumerations`), 5271then :ref:`Numerical Equality Operators` or :ref:`String Equality Operators` 5272are used depending on the kind of enumeration constant value 5273(:ref:`Enumeration Integer Values` or :ref:`Enumeration String Values`). 5274Otherwise, a :index:`compile-time error` occurs. 5275 5276.. index:: 5277 value equality 5278 enumeration type 5279 enumeration constant value 5280 constant value 5281 5282| 5283 5284.. _Function Type Equality Operators: 5285 5286Function Type Equality Operators 5287================================ 5288 5289.. meta: 5290 frontend_status: None 5291 5292If both operands refer to the same function object, then the comparison 5293returns ``true``. Otherwise, it is ``false``. 5294 5295 5296.. code-block:: typescript 5297 :linenos: 5298 5299 function foo() {} 5300 function bar() {} 5301 function goo(p: number) {} 5302 5303 foo == foo // true, same function object 5304 foo == bar // false, different function objects 5305 foo == goo // false, different function objects 5306 5307 class A { 5308 method() {} 5309 static method() {} 5310 foo () {} 5311 } 5312 const a = new A 5313 a.method == a.method // true, same function object 5314 A.method == A.method // true, same function object 5315 5316 const aa = new A 5317 a.method == aa.method /* false, different function objects 5318 as 'a' and 'aa' are different bounded objects */ 5319 a.method == a.foo // false, different function objects 5320 5321 5322.. index:: 5323 function type 5324 5325 5326| 5327 5328.. _Reference Equality Based on Actual Type: 5329 5330Reference Equality Based on Actual Type 5331======================================= 5332 5333.. meta: 5334 frontend_status: Done 5335 5336If an operand of an equality operator is of type ``Object``, a union type, 5337an interface type, or is a type parameter, then the operator is evaluated at 5338runtime, and is based on the actual type of this operand. If the other operand 5339is of a type other than that above, then the static type of this operand is 5340used for evaluation. 5341 5342If actual types of objects are compatible, then the corresponding evaluation of 5343equality operator is used. Otherwise, the result of the operators '``==``' and 5344'``===``' is ``false``. 5345 5346.. index:: 5347 reference equality 5348 union type 5349 operand 5350 compatibility 5351 equality operator 5352 object 5353 type parameter 5354 evaluation 5355 operator 5356 5357| 5358 5359.. _Object Type Equality Operators: 5360 5361Object Type Equality Operators 5362------------------------------ 5363 5364.. meta: 5365 frontend_status: Done 5366 5367A value of type ``Object`` can be compared to a value of any reference type. 5368 5369The following example illustrates an equality with a value of type ``Object``: 5370 5371.. code-block:: typescript 5372 :linenos: 5373 5374 function equToString(a: Object, b: string): boolean { 5375 return a == b 5376 } 5377 5378 equToString("aa", "aa") // true, string equality 5379 equToString(1, "aa") // false, not compatible types 5380 5381 function equ(a: Object, b: Object): boolean { 5382 return a == b 5383 } 5384 5385 equ(1, 1) // true, numerical equality 5386 equ(1, 2) // false, numerical equality 5387 5388 equ("aa", "aa") // true, string equality 5389 equ(1, "aa") // false, not compatible types 5390 5391.. index:: 5392 object type 5393 equality operator 5394 value 5395 compatible type 5396 compatibility 5397 5398**Note**. The actual type of an ``Object`` value can be none of the following: 5399 5400- Union type, as only the current value of a union type variable can be assigned 5401 to an ``Object`` variable; 5402 5403- Type parameter, if it has no type constraint (see 5404 :ref:`Type Parameter Constraint`) as in the example below: 5405 5406.. code-block:: typescript 5407 :linenos: 5408 5409 function check(a: Object) {} 5410 5411 class MyType {} 5412 5413 class G<A, B extends MyType> { 5414 foo(x: A, y: B) { 5415 check(x) // compile-type error, A is not assignable to Object 5416 check(y) // ok, B is assignable to Object as its constraint does 5417 } 5418 } 5419 5420.. index:: 5421 value 5422 union type 5423 variable 5424 type constraint 5425 assignment 5426 constraint 5427 type parameter 5428 object type 5429 5430| 5431 5432.. _Union Equality Operators: 5433 5434Union Equality Operators 5435------------------------ 5436 5437Where one operand is of type ``T``:sub:`1`, and the other operand is of type 5438``T``:sub:`2`, while ``T``:sub:`1`, ``T``:sub:`2`, or both are a union type, 5439then a :index:`compile-time error` occurs if ``T``:sub:`1` and ``T``:sub:`2` 5440have no overlap (i.e., if no value belongs to both ``T``:sub:`1` and 5441``T``:sub:`2`). 5442 5443**Note**. Any union type has an overlap with a value of type ``Object``. 5444 5445The following example illustrates an equality with values of two union types: 5446 5447.. code-block:: typescript 5448 :linenos: 5449 5450 function f1(x: number | string, y: boolean | null): boolean { 5451 return x == y // compile-time error, types have no overlap 5452 } 5453 5454 function f2(x: number | string, y: boolean | "abc"): boolean { 5455 return x == y // ok, types have overlap - value "abc" 5456 } 5457 5458.. index:: 5459 union equality 5460 equality operator 5461 type 5462 operand 5463 union type 5464 value 5465 object type 5466 5467If actual types of values are compatible, then the corresponding evaluation of 5468an equality operator is used. Otherwise, the result of the operators '``==``' 5469and '``===``' is ``false``: 5470 5471.. code-block:: typescript 5472 :linenos: 5473 5474 function equ(x: number | string, y: string): boolean { 5475 return x == y 5476 } 5477 5478 console.log(equ("aa", "aa")) // string equality: prints true 5479 console.log(equ("ab", "aa")) // string equality: prints false 5480 console.log(equ(1, "aa")) // different types: prints false 5481 5482.. index:: 5483 compatibility 5484 evaluation 5485 equality operator 5486 value 5487 operator 5488 5489| 5490 5491.. _Type Parameter Equality Operators: 5492 5493Type Parameter Equality Operators 5494--------------------------------- 5495 5496.. meta: 5497 frontend_status: Done 5498 5499If one operand is a type parameter, then the other operand can be of any 5500reference type, including type parameter. 5501 5502If actual object types are compatible, then the corresponding evaluation of an 5503equality operator is used. Otherwise, the result of the operators '``==``' and 5504'``===``' is ``false``: 5505 5506.. code-block:: typescript 5507 :linenos: 5508 5509 function equ<A>(x: A, y: A): boolean { 5510 return x == y 5511 } 5512 5513 console.log(equ<string>("aa", "aa")) // string equality: prints true 5514 console.log(equ<number>(1, 2)) // numerical equality: prints false 5515 5516.. index:: 5517 equality operator 5518 type parameter 5519 operand 5520 reference type 5521 compatibility 5522 evaluation 5523 5524| 5525 5526.. _Reference Equality: 5527 5528Reference Equality 5529================== 5530 5531.. meta: 5532 frontend_status: Partly 5533 todo: adapt latest specification changes 5534 5535Reference equality compares operands of two reference types except types 5536``string``, ``bigint``, ``Object``, union types, and type parameters. The 5537extended semantics is discussed in :ref:`Extended Equality with null or undefined`. 5538 5539A :index:`compile-time error` occurs if: 5540 5541- Any operand is not of a reference type; 5542 5543- There is no implicit conversion (see :ref:`Implicit Conversions`) that 5544 can convert type of either operand to the type of the other operand. 5545 5546The result of '``==``' or '``===``' is ``true`` if both operand values: 5547 5548- Are ``null``; 5549- Are ``undefined``; or 5550- Refer to the same object, array, or function. 5551 5552In addition, the result of the '``==``' operator is ``true`` if one operand 5553value is ``null``, and the other operand value is ``undefined``. Otherwise, 5554the result is ``false``. This semantics is illustrated by the example below: 5555 5556.. index:: 5557 reference equality 5558 reference type 5559 union type 5560 extended equality 5561 operand 5562 entity 5563 null 5564 undefined 5565 array 5566 operator 5567 operand value 5568 semantics 5569 5570.. code-block:: typescript 5571 :linenos: 5572 5573 class X {} 5574 new X() == new X() // false, two different object of class X 5575 new X() === new X() // false, the same 5576 let x1 = new X() 5577 let x2 = x1 5578 x1 == x2 // true, as x1 and x2 refer to the same object 5579 x1 === x2 // true, the same 5580 5581 new Number(5) === new Number(5) // true, value equality is used 5582 new Number(5) == new Number(6) // false, value equality is used 5583 5584 null == undefined // true 5585 null === undefined // false 5586 5587| 5588 5589.. _Extended Equality with null or undefined: 5590 5591Extended Equality with ``null`` or ``undefined`` 5592================================================ 5593 5594.. meta: 5595 frontend_status: Done 5596 5597|LANG| provides extended semantics for equalities with ``null`` and ``undefined`` 5598to ensure better alignment with |TS|. 5599 5600Any entity can be compared to ``null`` by using the operators '``==``' and 5601'``===``'. This comparison can return ``true`` only for the entities of 5602*nullable* types if they actually have the ``null`` value during program 5603execution. In all other cases the comparison to ``null`` returns ``false``. 5604 5605.. index:: 5606 extended equality 5607 semantics 5608 nullable type 5609 null 5610 operator 5611 entity 5612 5613Operators '``!=``' and '``!==``' return ``true`` for any entity of 5614*non-nullable* types, and for *nullable* entities if they actually have no 5615``null`` value during program execution. 5616 5617These situations are to be known at compile time. 5618 5619Similarly, an equality comparison to ``undefined`` returns ``false`` if the 5620variable being compared is neither type ``undefined`` nor a union type with 5621``undefined`` as one of its types. 5622 5623The following comparisons evaluate to ``false`` at compile time: 5624 5625.. code-block-meta: 5626 5627.. code-block:: typescript 5628 :linenos: 5629 5630 5 == null // false 5631 5 == undefined // false 5632 ((): void => {}) == null // false 5633 5634 class X {} 5635 new X() == null // false 5636 5637The following comparison is evaluated at runtime: 5638 5639.. code-block:: typescript 5640 :linenos: 5641 5642 function foo<T> (p1: string | null, p2: T) { 5643 console.log (p1 == undefined, p1 == null, p2 == undefined, p2 == null) 5644 } 5645 let nullable: string|null = "a string" 5646 let undefinedable: Object|undefined = undefined 5647 5648 foo (nullable, undefinedable) // Output: false false true true 5649 5650.. index:: 5651 entity 5652 non-nullable type 5653 nullable type 5654 null 5655 variable 5656 equality 5657 comparison 5658 undefined 5659 evaluation 5660 runtime 5661 5662| 5663 5664.. _Bitwise and Logical Expressions: 5665 5666Bitwise and Logical Expressions 5667******************************* 5668 5669.. meta: 5670 frontend_status: Done 5671 5672The *bitwise operators* and *logical operators* are as follows: 5673 5674- AND operator '``&``'; 5675- Exclusive OR operator '``^``'; and 5676- Inclusive OR operator '``|``'. 5677 5678The syntax of *bitwise and logical expression* is presented below: 5679 5680.. code-block:: abnf 5681 5682 bitwiseAndLogicalExpression: 5683 expression '&' expression 5684 | expression '^' expression 5685 | expression '|' expression 5686 ; 5687 5688These operators have different precedence. The operator '``&``' has the highest, 5689while '``|``' has the lowest precedence. 5690 5691Operators group left-to-right. Each operator is commutative if the 5692operand expressions have no side effects, and associative. 5693 5694The bitwise and logical operators can compare two operands of a numeric 5695type, or two operands of the ``boolean`` type. Otherwise, a 5696:index:`compile-time error` occurs. 5697 5698.. index:: 5699 bitwise operator 5700 logical operator 5701 bitwise expression 5702 logical expression 5703 type boolean 5704 operand expression 5705 exclusive OR operator 5706 inclusive OR operator 5707 AND operator 5708 commutative operator 5709 boolean type 5710 side effect 5711 numeric type 5712 associativity 5713 operator 5714 5715| 5716 5717.. _Integer Bitwise Operators: 5718 5719Integer Bitwise Operators 5720========================= 5721 5722.. meta: 5723 frontend_status: Done 5724 5725Bitwise operators '``&``', '``^``', and '``|``' are applied to operands 5726of numeric types or type ``bigint``. 5727 5728If the type of one or both operands is ``double`` or ``float``, then the operand 5729or operands are truncated first to the appropriate integer type. 5730If the type of any operand is ``byte`` or ``short``, then the operand is 5731converted to ``int``. 5732If operands are of different integer types, then the operand of the smaller type 5733is converted to the larger type (see :ref:`Numeric types`) by using 5734:ref:`Widening Numeric Conversions`. 5735If both operands are of type ``bigint``, then no conversion is required. 5736A :index:`compile-time error` occurs if one operand of type ``bigint``, and the 5737other operand is of a numeric type. 5738 5739The resultant type of the bitwise operator is the type of its operands. 5740 5741The resultant value of '``&``' is the bitwise AND of the operand values. 5742 5743The resultant value of '``^``' is the bitwise exclusive OR of the operand values. 5744 5745The resultant value of '``|``' is the bitwise inclusive OR of the operand values. 5746 5747.. index:: 5748 integer bitwise operator 5749 numeric types conversion 5750 numeric type 5751 conversion 5752 convertibility 5753 types conversion 5754 bitwise exclusive OR operand 5755 bitwise inclusive OR operand 5756 bitwise AND operand 5757 expression type 5758 operand value 5759 integer type 5760 conversion 5761 truncation 5762 5763| 5764 5765.. _Boolean Logical Operators: 5766 5767Boolean Logical Operators 5768========================= 5769 5770.. meta: 5771 frontend_status: Done 5772 5773Type of the bitwise operator expression is ``boolean``. Both operands of 5774operator '``&``', '``^``', or '``|``' must be of type ``boolean``. 5775 5776If both operand values are ``true``, then the resultant value of '``&``' is 5777``true``. Otherwise, the result is ``false``. 5778 5779If the operand values are different, then the resultant value of ‘``^``’ is 5780``true``. Otherwise, the result is ``false``. 5781 5782If both operand values are ``false``, then the resultant value of ‘``|``’ is 5783``false``. Otherwise, the result is ``true``. 5784 5785Thus, *boolean logical expression* is of the boolean type. 5786 5787.. index:: 5788 boolean operator 5789 logical operator 5790 bitwise operator expression 5791 conversion 5792 numeric types conversion 5793 numeric type 5794 operand value 5795 boolean logical expression 5796 boolean type 5797 5798| 5799 5800.. _Conditional-And Expression: 5801 5802Conditional-And Expression 5803************************** 5804 5805.. meta: 5806 frontend_status: Done 5807 5808The *conditional-and* operator '``&&``' is similar to '``&``' (see 5809:ref:`Bitwise and Logical Expressions`) but evaluates its right-hand-side 5810operand only if the value of the left-hand-side operand is ``true``. 5811 5812The results of computation of '``&&``' and '``&``' on ``boolean`` operands are 5813the same, but the right-hand-side operand in '``&&``' cannot be evaluated. 5814 5815The syntax of *conditional-and expression* is presented below: 5816 5817.. code-block:: abnf 5818 5819 conditionalAndExpression: 5820 expression '&&' expression 5821 ; 5822 5823A *conditional-and* operator groups left-to-right. 5824 5825A *conditional-and* operator is fully associative as regards both the result 5826value and side effects (i.e., the evaluations of the expressions *((a)* ``&&`` 5827*(b))* ``&&`` *(c)* and *(a)* ``&&`` *((b)* ``&&`` *(c))* produce the same 5828result, and the same side effects occur in the same order for any *a*, *b*, and 5829*c*). 5830 5831.. index:: 5832 conditional-and operator 5833 conditional-and expression 5834 bitwise expression 5835 logical expression 5836 boolean operand 5837 conditional evaluation 5838 evaluation 5839 expression 5840 5841A *conditional-and* expression is always of type ``boolean`` except the 5842extended semantics (see :ref:`Extended Conditional Expressions`). 5843A *conditional-and* expression with extended semantics can be of the first 5844expression type. 5845 5846Each operand of the *conditional-and* operator must be of type ``boolean``, 5847or of a type mentioned in :ref:`Extended Conditional Expressions`. 5848Otherwise, a :index:`compile-time error` occurs. 5849 5850The left-hand-side operand expression is first evaluated at runtime. 5851 5852If the resultant value is ``false``, then the value of the *conditional-and* 5853expression is ``false``. The evaluation of the right-hand-side operand 5854expression is omitted. 5855 5856If the value of the left-hand-side operand is ``true``, then the 5857right-hand-side expression is evaluated. 5858The resultant value is the value of the *conditional-and* 5859expression. 5860 5861.. index:: 5862 conditional-and expression 5863 conditional-and operator 5864 compile-time error 5865 boolean type 5866 predefined numeric types conversion 5867 numeric types conversion 5868 numeric type 5869 evaluation 5870 5871| 5872 5873.. _Conditional-Or Expression: 5874 5875Conditional-Or Expression 5876************************* 5877 5878.. meta: 5879 frontend_status: Done 5880 5881The *conditional-or* operator '``||``' is similar to '``|``' (see 5882:ref:`Integer Bitwise Operators`) but evaluates its right-hand-side operand 5883only if the value of its left-hand-side operand is ``false``. 5884 5885The syntax of *conditional-or expression* is presented below: 5886 5887.. code-block:: abnf 5888 5889 conditionalOrExpression: 5890 expression '||' expression 5891 ; 5892 5893A *conditional-or* operator groups left-to-right. 5894 5895A *conditional-or* operator is fully associative as regards both the result 5896value and side effects (i.e., the evaluations of the expressions *((a)* ``||`` 5897*(b))* ``||`` *(c)* and *(a)* ``||`` *((b)* ``||`` *(c))* produce the same 5898result, and the same side effects occur in the same order for any *a*, *b*, 5899and *c*). 5900 5901A *conditional-or* expression is always of type ``boolean`` except the 5902extended semantics (see :ref:`Extended Conditional Expressions`). 5903A *conditional-or* expression with extended semantics can be of the first 5904expression type. 5905 5906.. index:: 5907 conditional-or expression 5908 conditional-or operator 5909 integer bitwise expression 5910 associativity 5911 expression 5912 side effect 5913 evaluation 5914 boolean type 5915 semantics 5916 boolean type 5917 extended semantics 5918 5919Each operand of the *conditional-or* operator must be of type ``boolean`` 5920or type mentioned in :ref:`Extended Conditional Expressions`. 5921Otherwise, a :index:`compile-time error` occurs. 5922 5923The left-hand-side operand expression is first evaluated at runtime. 5924 5925If the resultant value is ``true``, then the value of the *conditional-or* 5926expression is ``true``, and the evaluation of the right-hand-side operand 5927expression is omitted. 5928 5929If the resultant value is ``false``, then the right-hand-side expression is 5930evaluated. 5931The resultant value is the value of the *conditional-or* expression. 5932 5933The computation results of '``||``' and '``|``' on ``boolean`` operands are 5934the same, but the right-hand-side operand in '``||``' cannot be evaluated. 5935 5936.. index:: 5937 conditional-or expression 5938 conditional-or operator 5939 runtime 5940 boolean type 5941 expression 5942 boolean operand 5943 numeric types conversion 5944 numeric type 5945 semantics 5946 conditional evaluation 5947 5948| 5949 5950.. _Assignment: 5951 5952Assignment 5953********** 5954 5955.. meta: 5956 frontend_status: Done 5957 5958All *assignment operators* group right-to-left (i.e., :math:`a=b=c` means 5959:math:`a=(b=c)`. The value of *c* is thus assigned to *b*, and then the value 5960of *b* to *a*). 5961 5962The syntax of *assignment expression* is presented below: 5963 5964.. code-block:: abnf 5965 5966 assignmentExpression: 5967 lhsExpression assignmentOperator rhsExpression 5968 ; 5969 5970 assignmentOperator 5971 : '=' 5972 | '+=' | '-=' | '*=' | '=' | '%=' | `**=` 5973 | '<<=' | '>>=' | '>>>=' 5974 | '&=' | '|=' | '^=' | `&&=` | `||=` 5975 | `??=` 5976 ; 5977 5978 lhsExpression: 5979 expression 5980 ; 5981 5982 rhsExpression: 5983 expression 5984 ; 5985 5986The first operand in an assignment operator represented by *lhsExpression* must 5987be *left-hand-side expression* (see :ref:`Left-Hand-Side Expressions`). This 5988first operand denotes a variable. 5989 5990.. index:: 5991 assignment 5992 assignment operator 5993 operand 5994 variable 5995 expression 5996 5997Type of the variable is the type of the assignment expression. 5998 5999The result of the *assignment expression* at runtime is not a variable itself 6000but the value of a variable after the assignment. 6001 6002.. index:: 6003 variable 6004 assignment 6005 assignment expression 6006 value 6007 runtime 6008 6009| 6010 6011.. _Simple Assignment Operator: 6012 6013Simple Assignment Operator 6014========================== 6015 6016.. meta: 6017 frontend_status: Done 6018 6019The form of a simple assignment expression is ``lhsExpression = rhsExpression``. 6020 6021A :index:`compile-time error` occurs if type of *rhsExpression* 6022is not assignable (see :ref:`Assignability`) to 6023the type of the variable. Otherwise, the assignment expression is evaluated 6024at runtime in one of the following ways: 6025 60261. If *lhsExpression* is a field access expression 6027 ``e.f`` (see :ref:`Field Access Expression`), possibly enclosed in parentheses, 6028 then: 6029 6030 #. *lhsExpression* *e* is evaluated: if the evaluation of *e* 6031 completes abruptly, then so does the assignment expression. 6032 #. *rhsExpression* is evaluated: if the evaluation 6033 completes abruptly, then so does the assignment expression. 6034 #. Value of *rhsExpression* as computed above is assigned 6035 to the variable denoted by ``e.f``. 6036 6037.. index:: 6038 simple assignment operator 6039 operator 6040 assignable type 6041 assignability 6042 access 6043 field access 6044 field access expression 6045 runtime 6046 abrupt completion 6047 evaluation 6048 assignment expression 6049 variable 6050 60512. If the *lhsExpression* is an array reference expression (see 6052 :ref:`Array Indexing Expression`), possibly enclosed in parentheses, then: 6053 6054 #. Array reference subexpression of *lhsExpression* is evaluated. 6055 If this evaluation completes abruptly, then so does the assignment 6056 expression. In that case, *rhsExpression* and the index 6057 subexpression are not evaluated, and the assignment does not occur. 6058 #. If the evaluation completes normally, then the index subexpression of 6059 *lhsExpression* is evaluated. If this evaluation completes abruptly, 6060 then so does the assignment expression. In that case, *rhsExpression* 6061 is not evaluated, and the assignment does not occur. 6062 #. If the evaluation completes normally, then *rhsExpression* is 6063 evaluated. If this evaluation completes abruptly, then so does the 6064 assignment expression, and the assignment does not occur. 6065 #. If the evaluation completes normally, but the value of the index 6066 subexpression is less than zero, or greater than, or equal to the 6067 *length* of the array, then ``ArrayIndexOutOfBoundsError`` is thrown, 6068 and the assignment does not occur. 6069 #. Otherwise, the value of the index subexpression is used to select an 6070 element of the array referred to by the value of the array reference 6071 subexpression. 6072 6073 The value of *rhsExpression* is assigned to the array element. 6074 6075.. index:: 6076 operand 6077 array reference expression 6078 parenthesis 6079 array indexing expression 6080 reference subexpression 6081 assignment 6082 assignment expression 6083 abrupt completion 6084 subexpression 6085 evaluation 6086 array element 6087 array length 6088 variable 6089 conversion 6090 array element 6091 value set 6092 extended exponent 6093 reference type 6094 assignable class 6095 assignability 6096 runtime 6097 60983. If *lhsExpression* is a record access expression (see 6099 :ref:`Record Indexing Expression`), possibly enclosed in parentheses, then: 6100 6101 #. Object reference subexpression of *lhsExpression* is evaluated. 6102 If this evaluation completes abruptly, then so does the assignment 6103 expression. 6104 In that case, *rhsExpression* and the index subexpression are 6105 not evaluated, and the assignment does not occur. 6106 #. If the evaluation completes normally, the index subexpression of 6107 *lhsExpression* is evaluated. If this evaluation completes abruptly, 6108 then so does the assignment expression. 6109 In the last case, *rhsExpression* is not evaluated, and the 6110 assignment does not occur. 6111 #. If the evaluation completes normally, *rhsExpression* is 6112 evaluated. If this evaluation completes abruptly, then so does the 6113 assignment expression. In that case, the assignment does not occur. 6114 #. Otherwise, the value of the index subexpression is used as the ``key``. 6115 In that case, the value of *rhsExpression* is used as the ``value``, and 6116 the key-value pair is stored in the record instance. 6117 6118.. index:: 6119 operand 6120 record access expression 6121 parenthesis 6122 access expression 6123 reference subexpression 6124 index subexpression 6125 assignment 6126 assignment expression 6127 evaluation 6128 value 6129 key-value pair 6130 record instance 6131 normal completion 6132 abrupt completion 6133 key 6134 6135 6136If none of the above is true, then the following three steps are required: 6137 6138#. *lhsExpression* is evaluated to produce a variable. If the 6139 evaluation completes abruptly, then so does the assignment expression. 6140 In that case, *rhsExpression* is not evaluated, and the 6141 assignment does not occur. 6142 6143#. If the evaluation completes normally, then *rhsExpression* is 6144 evaluated. If the evaluation completes abruptly, then so does the assignment 6145 expression. In that case, the assignment does not occur. 6146 6147#. If that evaluation completes normally, then the value of *rhsExpression* 6148 is converted to the type of the left-hand-side variable. 6149 In that case, the result of the conversion is stored into the variable. 6150 A :index:`compile-time error` occurs if type of *lhsExpression* 6151 is one of the following: 6152 6153 - ``readonly`` array (see :ref:`Readonly Parameters`), while the 6154 converted type of *rhsExpression* is a non-``readonly`` array; 6155 - ``readonly`` tuple (see :ref:`Readonly Parameters`), while the 6156 converted type of *rhsExpression* is a non-``readonly`` tuple. 6157 6158.. index:: 6159 evaluation 6160 operand 6161 assignment expression 6162 assignment 6163 abrupt completion 6164 normal completion 6165 conversion 6166 variable 6167 readonly array 6168 readonly tuple 6169 converted type 6170 6171| 6172 6173.. _Compound Assignment Operators: 6174 6175Compound Assignment Operators 6176============================= 6177 6178.. meta: 6179 frontend_status: Done 6180 6181A compound assignment expression in the form: 6182 6183``lhsExpression op= rhsExpression`` 6184 6185is equivalent to 6186 6187``lhsExpression = ((lhsExpression) op (rhsExpression)) as T`` 6188 6189where ``T`` is type of *lhsExpression*, except that *lhsExpression* 6190is evaluated only once. 6191 6192While the nullish coalescing assignment (``??=``) only evaluates the right 6193operand, and assigns to the left operand if the left operand is ``null`` or 6194``undefined``. 6195 6196An assignment expression can be evaluated at runtime in one 6197of the following ways: 6198 61991. If *lhsExpression* is not an indexing expression: 6200 6201 - *lhsExpression* is evaluated to produce a variable. If the 6202 evaluation completes abruptly, then so does the assignment expression. 6203 In that case, *rhsExpression* is not evaluated, and no 6204 assignment occurs. 6205 6206 - If the evaluation completes normally, then the value of *lhsExpression* 6207 is saved, and *rhsExpression* is evaluated. If the 6208 evaluation completes abruptly, then so does the assignment expression. 6209 In that case, no assignment occurs. 6210 6211 - If the evaluation completes normally, then the saved value of the 6212 left-hand-side variable, and the value of *rhsExpression* are 6213 used to perform the binary operation as indicated by the compound 6214 assignment operator. If the operation completes abruptly, then so does 6215 the assignment expression. In that case, no assignment occurs. 6216 6217 - If the evaluation completes normally, then the result of the binary 6218 operation converts to the type of the left-hand-side variable. 6219 The result of such conversion is stored into the variable. 6220 6221.. index:: 6222 compound assignment operator 6223 assignment operator 6224 indexing expression 6225 evaluation 6226 expression 6227 runtime 6228 operand 6229 variable 6230 assignment 6231 abrupt completion 6232 normal completion 6233 assignment expression 6234 binary operation 6235 conversion 6236 62372. If *lhsExpression* is an array reference expression (see 6238 :ref:`Array Indexing Expression`), then: 6239 6240 - Array reference subexpression of *lhsExpression* is evaluated. 6241 If the evaluation completes abruptly, then so does the assignment 6242 expression. In that case, the index 6243 subexpression, and *rhsExpression* are not evaluated, 6244 and no assignment occurs. 6245 6246 - If the evaluation completes normally, then the index subexpression of 6247 *lhsExpression* is evaluated. If the evaluation completes abruptly, 6248 then so does the assignment expression. In that case, *rhsExpression* 6249 is not evaluated, and no assignment occurs. 6250 6251 - If the evaluation completes normally, the value of the array 6252 reference subexpression refers to an array, and the value of the 6253 index subexpression is less than zero, greater than, or equal to 6254 the *length* of the array, then ``ArrayIndexOutOfBoundsError`` is 6255 thrown. In that case, no assignment occurs. 6256 6257 - If the evaluation completes normally, then the value of the index 6258 subexpression is used to select an array element referred to by 6259 the value of the array reference subexpression. The value of this 6260 element is saved, and then *rhsExpression* is evaluated. 6261 If the evaluation completes abruptly, then so does the assignment 6262 expression. In that case, no assignment occurs. 6263 6264 - If the evaluation completes normally, consideration must be given 6265 to the saved value of the array element selected in the previous 6266 step. While this element is a variable of type ``S``, and ``T`` is 6267 type of *lhsExpression* of the assignment operator 6268 determined at compile time: 6269 6270 6271 - If ``T`` is a primitive type, then ``S`` is the same as ``T``. 6272 6273 The saved value of the array element, and the value of 6274 *rhsExpression* are used to perform the binary operation of the 6275 compound assignment operator. 6276 6277 If this operation completes abruptly, then so does the assignment 6278 expression. In that case, no assignment occurs. 6279 6280 If this evaluation completes normally, then the result of the binary 6281 operation converts to the type of the selected array element. 6282 The result of the conversion is stored into the array element. 6283 6284 - If ``T`` is a reference type, then it must be ``string``. 6285 6286 ``S`` must also be a ``string`` because the class ``string`` is the 6287 *final* class. The saved value of the array element, and the value of 6288 *rhsExpression* are used to perform the binary operation (string 6289 concatenation) of the compound assignment operator '``+=``'. If 6290 this operation completes abruptly, then so does the assignment 6291 expression. In that case, no assignment occurs. 6292 6293 - If the evaluation completes normally, then the ``string`` result of 6294 the binary operation is stored into the array element. 6295 6296.. index:: 6297 value 6298 array element 6299 operand 6300 expression 6301 array reference expression 6302 array indexing expression 6303 reference subexpression 6304 evaluation 6305 assignment subexpression 6306 index subexpression 6307 normal completion 6308 abrupt completion 6309 array length 6310 assignment 6311 subexpression 6312 variable 6313 assignment operator 6314 primitive type 6315 array element 6316 value 6317 operand 6318 binary operation 6319 assignment expression 6320 assignment 6321 conversion 6322 array element 6323 compound assignment operator 6324 string 6325 evaluation 6326 array 6327 string concatenation 6328 63293. If *lhsExpression* is a record access expression (see 6330 :ref:`Record Indexing Expression`): 6331 6332 - The object reference subexpression of *lhsExpression* is 6333 evaluated. If this evaluation completes abruptly, then so does the 6334 assignment expression. In that case, the index subexpression 6335 and *rhsExpression* are not evaluated, and no assignment occurs. 6336 6337 - If this evaluation completes normally, then the index subexpression of 6338 *lhsExpression* is evaluated. If the evaluation completes abruptly, 6339 then so does the assignment expression. In that case, *rhsExpression* 6340 is not evaluated, and no assignment occurs. 6341 6342 - If this evaluation completes normally, the value of the object reference 6343 subexpression and the value of index subexpression are saved, then 6344 *rhsExpression* is evaluated. If the evaluation completes 6345 abruptly, then so does the assignment expression. In that case, no 6346 assignment occurs. 6347 6348 - If this evaluation completes normally, the saved values of the object 6349 reference subexpression and index subexpression (as the *key*) are used 6350 to get the *value* that is mapped to the *key* (see 6351 :ref:`Record Indexing Expression`), then this *value* and the value of 6352 *rhsExpression* are used to perform the binary operation as 6353 indicated by the compound assignment operator. If the operation 6354 completes abruptly, then so does the assignment expression. In that case, 6355 no assignment occurs. 6356 6357 - If the evaluation completes normally, then the result of the binary 6358 operation is stored as the key-value pair in the record instance 6359 (as in :ref:`Simple Assignment Operator`). 6360 6361.. index:: 6362 record access expression 6363 operand expression 6364 record indexing expression 6365 object reference subexpression 6366 operand 6367 index subexpression 6368 evaluation 6369 assignment expression 6370 abrupt completion 6371 normal completion 6372 assignment 6373 object reference subexpression 6374 reference subexpression 6375 index subexpression 6376 key 6377 key-value pair 6378 record indexing expression 6379 indexing expression 6380 record instance 6381 value 6382 compound assignment operator 6383 binary operation 6384 6385| 6386 6387.. _Left-Hand-Side Expressions: 6388 6389Left-Hand-Side Expressions 6390========================== 6391 6392.. meta: 6393 frontend_status: Done 6394 6395*Left-hand-side expression* is an *expression* that is one of the following: 6396 6397- Named variable; 6398- Field or setter resultant from a field access (see 6399 :ref:`Field Access Expression`); or 6400- Array or record element access (see :ref:`Indexing Expressions`). 6401 6402A :index:`compile-time error` occurs in the following situations: 6403 6404- *Expression* contains the chaining operator '``?.``' (see 6405 :ref:`Chaining Operator`); 6406- Result of *expression* is not a variable. 6407 6408.. index:: 6409 expression 6410 named variable 6411 field 6412 setter 6413 field access 6414 array element 6415 record element 6416 access 6417 indexing expression 6418 chaining operator 6419 variable 6420 6421| 6422 6423 6424.. _Conditional Expressions: 6425 6426Conditional Expressions 6427*********************** 6428 6429.. meta: 6430 frontend_status: Done 6431 todo: implement full LUB support (now only basic LUB implemented) 6432 6433The conditional expression '``? :``' uses the boolean value of the first 6434expression to decide which of the other two expressions to evaluate: 6435 6436.. code-block:: abnf 6437 6438 conditionalExpression: 6439 expression '?' expression ':' expression 6440 ; 6441 6442The conditional operator '``? :``' groups right-to-left (i.e., the meaning of 6443:math:`a?b:c?d:e?f:g` and :math:`a?b:(c?d:(e?f:g))` is the same). 6444 6445The conditional operator '``? :``' consists of three operand expressions 6446with the separators '``?``' between the first and the second expression, and 6447'``:``' between the second and the third expression. 6448 6449A :index:`compile-time error` occurs if the first expression is not of type 6450``boolean``, or a type mentioned in 6451:ref:`Extended Conditional Expressions`. 6452 6453.. index:: 6454 conditional expression 6455 boolean value 6456 expression 6457 conditional operator 6458 operand 6459 operand expression 6460 separator 6461 boolean type 6462 extended conditional expression 6463 6464Type of the conditional expression is determined as the union of types of the 6465second and the third expressions further normalized in accordance with the 6466process discussed in :ref:`Union Types Normalization`. If the second and the 6467third expressions are of the same type, then this is the type of the 6468conditional expression. 6469 6470The following steps are performed as the evaluation of a conditional expression 6471occurs at runtime: 6472 6473#. The operand expression of a conditional expression is evaluated first. 6474 6475#. If the value of the first operand is ``true``, then the second operand 6476 expression is evaluated. Otherwise, the third operand expression is 6477 evaluated. The result of successful evaluation is the result of the 6478 conditional expression. 6479 6480The examples below represent different scenarios with standalone expressions: 6481 6482.. code-block:: typescript 6483 :linenos: 6484 6485 class A {} 6486 class B extends A {} 6487 6488 condition ? new A() : new B() // A | B => A 6489 6490 condition ? 5 : 6 // int 6491 6492 condition ? "5" : 6 // "5" | int 6493 6494.. index:: 6495 conditional expression 6496 normalization 6497 union type 6498 evaluation 6499 operand expression 6500 conversion 6501 standalone expression 6502 6503| 6504 6505.. _String Interpolation Expressions: 6506 6507String Interpolation Expressions 6508******************************** 6509 6510.. meta: 6511 frontend_status: Done 6512 6513'*String interpolation expression*' is a multiline string literal (a string 6514literal delimited with backticks, see :ref:`Multiline String Literal` for 6515details) that contains at least one *embedded expression*. 6516 6517The syntax of *string interpolation expression* is presented below: 6518 6519.. code-block:: abnf 6520 6521 stringInterpolation: 6522 '`' (BacktickCharacter | embeddedExpression)* '`' 6523 ; 6524 6525 embeddedExpression: 6526 '${' expression '}' 6527 ; 6528 6529An '*embedded expression*' is an expression specified inside curly braces 6530preceded by the *dollar sign* '``$``'. A string interpolation expression is of 6531type ``string`` (see :ref:`Type String`). 6532 6533When evaluating a *string interpolation expression*, the result of each 6534embedded expression substitutes that embedded expression. An embedded 6535expression must be of type ``string``. Otherwise, the implicit conversion 6536to ``string`` takes place in the same way as with the string concatenation 6537operator (see :ref:`String Concatenation`): 6538 6539.. index:: 6540 string interpolation expression 6541 multiline string 6542 string literal 6543 backtick 6544 string type 6545 expression 6546 string 6547 curly brace 6548 concatenation 6549 embedded expression 6550 string concatenation operator 6551 implicit conversion 6552 embedded expression 6553 6554.. code-block:: typescript 6555 :linenos: 6556 6557 let a = 2 6558 let b = 2 6559 console.log(`The result of ${a} * ${b} is ${a * b}`) 6560 // prints: The result of 2 * 2 is 4 6561 6562The string concatenation operator can be used to rewrite the above example 6563as follows: 6564 6565.. code-block:: typescript 6566 :linenos: 6567 6568 let a = 2 6569 let b = 2 6570 console.log("The result of " + a + " * " + b + " is " + a * b) 6571 6572An embedded expression can contain nested multiline strings. 6573 6574.. index:: 6575 string concatenation operator 6576 nested multiline string 6577 multiline string 6578 embedded expression 6579 6580| 6581 6582.. _Lambda Expressions: 6583 6584Lambda Expressions 6585****************** 6586 6587.. meta: 6588 frontend_status: Done 6589 6590*Lambda expression* fully defines an instance of a function type (see 6591:ref:`Function Types`) by providing optional ``async`` mark, type parameters 6592(see :ref:`Type Parameters`), mandatory lambda signature, and its body. The 6593definition of *lambda expression* is generally similar to that of a function 6594declaration (see :ref:`Function Declarations`), except that a lambda expression 6595has no function name specified, and can have types of parameters omitted. 6596 6597The syntax of *lambda expression* is presented below: 6598 6599.. code-block:: abnf 6600 6601 lambdaExpression: 6602 annotationUsage? 6603 ('async'|typeParameters)? lambdaSignature '=>' lambdaBody 6604 ; 6605 6606 lambdaBody: 6607 expression | block 6608 ; 6609 6610 lambdaSignature: 6611 '(' lambdaParameterList? ')' returnType? 6612 | identifier 6613 ; 6614 6615 lambdaParameterList: 6616 lambdaParameter (',' lambdaParameter)* (',' restParameter)? ','? 6617 | restParameter ','? 6618 ; 6619 6620 lambdaParameter: 6621 annotationUsage? (lambdaRequiredParameter | lambdaOptionalParameter) 6622 ; 6623 6624 lambdaRequiredParameter: 6625 identifier (':' type)? 6626 ; 6627 6628 lambdaOptionalParameter: 6629 identifier '?' (':' type)? 6630 ; 6631 6632 lambdaRestParameter: 6633 '...' lambdaRequiredParameter 6634 ; 6635 6636The usage of annotations is discussed in :ref:`Using Annotations`. 6637 6638.. index:: 6639 lambda expression 6640 instance 6641 function type 6642 async mark 6643 type parameter 6644 lambda signature 6645 function declaration 6646 annotation 6647 6648The examples of usage are presented below: 6649 6650.. code-block:: typescript 6651 :linenos: 6652 6653 (x: number): number => { return Math.sin(x) } // block as lambda body 6654 (x: number) => Math.sin(x) // expression as lambda body 6655 <T> (x: T, y: T) => { let local = x } // generic lambda 6656 e => e // shortest form of lambda 6657 6658A *lambda expression* evaluation creates an instance of a function type (see 6659:ref:`Function Types`) as described in detail in 6660:ref:`Runtime Evaluation of Lambda Expressions`. 6661 6662.. index:: 6663 lambda expression 6664 function type 6665 instance 6666 6667| 6668 6669.. _Lambda Signature: 6670 6671Lambda Signature 6672================ 6673 6674.. meta: 6675 frontend_status: Done 6676 6677Similarly to function declarations (see :ref:`Function Declarations`), 6678a *lambda signature* is composed of formal parameters and 6679optional return types. Unlike function declarations, 6680type annotations of formal parameters can be omitted. 6681 6682.. code-block:: typescript 6683 :linenos: 6684 6685 function foo<T> (a: (p1: T, ...p2: T[]) => T) {} 6686 // All calls to foo pass valid lambda expressions in different forms 6687 foo (e => e) 6688 foo ((e1, e2) => e1) 6689 foo ((e1, e2: Object) => e1) 6690 foo ((e1: Object, e2) => e1) 6691 foo ((e1: Object, e2, e3) => e1) 6692 foo ((e1: Object, ...e2) => e1) 6693 6694 foo (<Object>(e1: Object, e2: Object) => e1) 6695 6696 function bar<T> (a: (...p: T[]) => T) {} 6697 // Type can be omitted for the rest parameter 6698 bar ((...e) => e) 6699 6700 function goo<T> (a: (p?: T) => T) {} 6701 // Type can be omitted for the optional parameter 6702 goo ((e?) => e) 6703 6704 6705The specification of scope is discussed in :ref:`Scopes`, and shadowing details 6706of formal parameter declarations in :ref:`Shadowing by Parameter`. 6707 6708A :index:`compile-time error` occurs if: 6709 6710- Lambda expression declares two formal parameters with the same name. 6711- Formal parameter contains no type provided, and type cannot be derived 6712 by type inference. 6713 6714 6715.. index:: 6716 lambda signature 6717 return type 6718 lambda expression 6719 function declaration 6720 type annotation 6721 type inference 6722 annotation 6723 scope 6724 shadow parameter 6725 shadowing 6726 parameter declaration 6727 evaluation 6728 argument expression 6729 initialization 6730 variable 6731 execution 6732 lambda body 6733 6734| 6735 6736.. _Lambda Body: 6737 6738Lambda Body 6739=========== 6740 6741.. meta: 6742 frontend_status: Done 6743 6744*Lambda body* can be a single expression or a block (see :ref:`Block`). 6745Similarly to the body of a method or a function, a lambda body describes the 6746code to be executed when a lambda expression call occurs (see 6747:ref:`Function Call Expression`). 6748 6749The meanings of names, and of the keywords ``this`` and ``super`` (along with 6750the accessibility of the referred declarations) are the same as in the 6751surrounding context. However, lambda parameters introduce new names. 6752 6753If any local variable or formal parameter of the surrounding context is 6754used but not declared in a lambda body, then the local variable or formal 6755parameter is *captured* by the lambda. 6756 6757If an instance member of the surrounding type is used in the lambda body 6758defined in a method, then ``this`` is *captured* by the lambda. 6759 6760A :index:`compile-time error` occurs if a local variable is used in a lambda 6761body but is neither declared in nor assigned before it. 6762 6763If a *lambda body* is a single ``expression`` it is treated as 6764 6765- If the expression is a *call expression* with return type ``void`` 6766 the body is equivalent to the block: ``{ expression }`` 6767 6768- Otherwise, the body is equivalent to the block: ``{ return expression }`` 6769 6770If *lambda signature* return type is not ``void`` (see :ref:`Type void`), and 6771the execution path of the lambda body has no return statement (see 6772:ref:`Return Statements`) or no single expression as a body, then a 6773:index:`compile-time error` occurs. 6774 6775.. index:: 6776 lambda body 6777 lambda 6778 lambda expression 6779 keyword this 6780 keyword super 6781 this 6782 super 6783 runtime 6784 evaluation 6785 method body 6786 function body 6787 lambda call 6788 surrounding context 6789 accessibility 6790 lambda body 6791 lambda signature 6792 instance member 6793 surrounding type 6794 return statement 6795 assignment 6796 6797| 6798 6799.. _Lambda Expression Type: 6800 6801Lambda Expression Type 6802====================== 6803 6804.. meta: 6805 frontend_status: Done 6806 6807*Lambda expression type* is a function type (see :ref:`Function Types`) 6808that has the following: 6809 6810- Lambda parameters (if any) as parameters of the function type; and 6811 6812- Lambda return type as the return type of the function type. 6813 6814**Note**. Lambda return type can be inferred from the *lambda body* and thus 6815the return type can be dropped off. 6816 6817 .. code-block:: typescript 6818 :linenos: 6819 6820 const lambda = () => { return 123 } // Type of the lambda is () => int 6821 const int_var: int = lambda() 6822 6823 6824.. index:: 6825 lambda expression type 6826 function type 6827 lambda parameter 6828 lambda return type 6829 inference 6830 lambda body 6831 6832| 6833 6834.. _Runtime Evaluation of Lambda Expressions: 6835 6836Runtime Evaluation of Lambda Expressions 6837======================================== 6838 6839.. meta: 6840 frontend_status: Done 6841 6842The evaluation of a lambda expression itself never causes the execution of the 6843lambda body. If completing normally at runtime, the evaluation of a lambda 6844expression produces a reference to an allocated and initialized new instance 6845of a function type (see :ref:`Function Types`) that corresponds to the lambda 6846signature. In that case, it is similar to the evaluation of a class instance 6847creation expression (see :ref:`New Expressions`). 6848 6849If the available space is not sufficient for a new instance to be created, 6850then the evaluation of the lambda expression completes abruptly, and 6851``OutOfMemoryError`` is thrown. 6852 6853During a lambda expression evaluation, the captured values of the 6854lambda expression are saved to the internal state of the created instance. 6855 6856.. index:: 6857 runtime evaluation 6858 lambda expression 6859 lambda body 6860 execution 6861 initialization 6862 function type 6863 lambda signature 6864 normal completion 6865 instance creation expression 6866 initialization 6867 allocation 6868 instance 6869 abrupt completion 6870 error 6871 captured value 6872 internal state 6873 lambda expression evaluation 6874 6875 6876+-----------------------------------------------+--------------+ 6877| Source Fragment | Output | 6878+===============================================+==============+ 6879| .. code-block:: typescript || | 6880| :linenos: | | 6881| | | 6882| function foo() { | | 6883| let y: int = 1 | 2 | 6884| let x = () => { return y+1 } | | 6885| console.log(x()) | | 6886| } | | 6887+-----------------------------------------------+--------------+ 6888 6889The variable 'y' is *captured* by the lambda. 6890 6891The captured variable is not a copy of the original variable. If the 6892value of the variable captured by the lambda changes, then the original 6893variable is implied to change: 6894 6895.. index:: 6896 captured by lambda 6897 lambda 6898 variable 6899 captured variable 6900 original variable 6901 6902+-----------------------------------------------+--------------+ 6903| Source Fragment | Output | 6904+===============================================+==============+ 6905| .. code-block:: typescript || | 6906| :linenos: | | 6907| | | 6908| function foo() { | | 6909| let y: int = 1 | 1 | 6910| let x = () => { y++ } | | 6911| console.log(y) | 2 | 6912| x() | | 6913| console.log(y) | | 6914| } | | 6915+-----------------------------------------------+--------------+ 6916 6917In order to make lambdas behave as required, the language implementation 6918can act as follows: 6919 6920- Replace the captured variable’s type for a proxy class that contains an 6921 original reference (x: T for x: Proxy<T>; x.ref = original-ref) if that 6922 captured variable is of non-primitive type. 6923 6924If the captured variable is defined as ``const``, then 6925proxying is not required. 6926 6927If the captured formal parameter can be neither boxed nor proxied, then 6928the implementation can require addition of a local variable as follows: 6929 6930.. index:: 6931 lambda 6932 implementation 6933 primitive type 6934 proxy class 6935 captured variable 6936 captured variable type 6937 non-primitive type 6938 proxying 6939 local variable 6940 variable 6941 6942+-----------------------------------+-----------------------------------+ 6943| Source Code | Pseudo Code | 6944+===================================+===================================+ 6945| .. code-block:: typescript | .. code-block:: typescript | 6946| :linenos: | :linenos: | 6947| | | 6948| function foo(y: int) { | function foo(y: int) { | 6949| let x = () => { return y+1 } | let y$: Int = y | 6950| console.log(x()) | let x = () => { return y$+1 } | 6951| } | console.log(x()) | 6952| | } | 6953+-----------------------------------+-----------------------------------+ 6954 6955| 6956 6957.. _Constant Expressions: 6958 6959Constant Expressions 6960******************** 6961 6962.. meta: 6963 frontend_status: Done 6964 6965*Constant expressions* are expressions with values that can be evaluated at 6966compile time. 6967 6968The syntax of *constant expression* is presented below: 6969 6970.. code-block:: abnf 6971 6972 constantExpression: 6973 expression 6974 ; 6975 6976A *constant expression* is an expression of a value type (see 6977:ref:`Value Types`), or of type ``string`` that completes normally 6978while being composed only of the following: 6979 6980- Literals of a primitive type, and literals of type ``string`` (see 6981 :ref:`Literals`); 6982 6983- Enumeration type constants; 6984 6985- Unary operators '``+``', '``-``', '``~``', and '``!``', but not '``++``' 6986 or '``--``' (see :ref:`Unary Plus`, :ref:`Unary Minus`, 6987 :ref:`Prefix Increment`, and :ref:`Prefix Decrement`); 6988 6989- Casting conversions to numeric types (see :ref:`Cast Expression`); 6990 6991- Multiplicative operators '``*``', '``/``', and '``%``' (see 6992 :ref:`Multiplicative Expressions`); 6993 6994- Additive operators '``+``' and '``-``' (see :ref:`Additive Expressions`); 6995 6996- Shift operators '``<<``', '``>>``', and '``>>>``' (see 6997 :ref:`Shift Expressions`); 6998 6999- Relational operators '``<``', '``<=``', '``>``', and '``>=``' (see 7000 :ref:`Relational Expressions`); 7001 7002- Equality operators '``==``' and '``!=``' (see :ref:`Equality Expressions`); 7003 7004- Bitwise and logical operators '``&``', '``^``', and '``|``' (see 7005 :ref:`Bitwise and Logical Expressions`); 7006 7007- Conditional-and operator '``&&``' (see :ref:`Conditional-And Expression`), 7008 and conditional-or operator '``||``' (see :ref:`Conditional-Or Expression`); 7009 7010- Ternary conditional operator '``? :``' (see :ref:`Conditional Expressions`); 7011 7012- Parenthesized expressions (see :ref:`Parenthesized Expression`) that contain 7013 constant expressions; 7014 7015- Simple names or qualified names that refer to constants (see 7016 :ref:`Constant Declarations`) with constant expressions as initializers, 7017 declared in the same compilation unit. 7018 7019.. index:: 7020 constant expression 7021 primitive type 7022 string type 7023 enumeration type 7024 conversion 7025 normal completion 7026 literal 7027 cast expression 7028 unary operator 7029 increment operator 7030 decrement operator 7031 prefix 7032 multiplicative operator 7033 multiplicative expression 7034 shift operator 7035 relational operator 7036 equality operator 7037 bitwise operator 7038 logical operator 7039 ternary conditional operator 7040 conditional operator 7041 conditional-and operator 7042 conditional-or operator 7043 parenthesized expression 7044 constant expression 7045 simple name 7046 constant variable 7047 qualified name 7048 initializer 7049 compilation unit 7050 7051The examples of constant expressions are presented below: 7052 7053.. code-block:: typescript 7054 :linenos: 7055 7056 const a = 2 7057 7058 // Constant expressions: 7059 1 + 2 7060 a + 1 7061 "aa" + "bb" 7062 (a < 0) || (a > 5) 7063 7064**Note**. The following expressions are not constant expressions: 7065 7066.. code-block:: typescript 7067 :linenos: 7068 7069 let x = 2 7070 7071 // non-constant expressions: 7072 x + 1 7073 0x7f as short 7074 7075.. raw:: pdf 7076 7077 PageBreak 7078