Comp 110 TypeScript Syntax

TypeScript Language Constructs

Comment out content.

//This is a comment!
/* This is also a comment! */

Primitive types.

boolean, number, string

Declare a variable.

let <name>: <type>;

Initialize a variable.

<name> = <value>;

Declare and initialize a variable together. Adding the type here is unnecessary TypeScript will be able to infer the type of your variable from the type of the value it is given

let <name>: <type> = <value>;

Test Equality

<value> === <value>

Declare a function.

let <function name> = (<parameters>): <return type> => {

Using a while loop.

// declare and initialize counter
while (<boolean expression>) {
    // do something
    // increment counter or set boolean expression to false

Using for loop.

for (<declare and initialize counter>; <boolean expression>; <increment counter> {
// do something

Declare an array. (Type is implied by the contents of the array. If multiple types are provided, array will be of type 'any.')

let <name>: <type>[] = [];
//This is currently initialized to be an empty array

Declare a 2D array.

let <name>: <type>[][];
//initializing these arrays to values often uses a helper function

Defining a class/properties/constructor/method.

Class <class name> {
     <property name>:<property type>; //this property doesn't have a default value assigned
     <property name=""> = <property default value> // this property does
     constructor (<parameter name>:<parameter type>, <parameter name="">:<parameter type=""></parameter></parameter>) {
          this.<property name> = <parameter name>;
          this.<property name> = <parameter name>; 
     } //when this constructor ends, all the properties of the object will have a value
     <method name> = (<parameter name>:<parameter type>):<return type> => {
          //method body

Constructing an object.

let <object name> = new <class name/type>(<arguments for constructor>);

Calling a method on an object.

<object name>.<method name>(<method arguments>);
//the object itself will be the "this" in the method call