TypeScript - Basic Syntax


Advertisements


Syntax defines a set of rules for writing programs. Every language specification defines its own syntax. A TypeScript program is composed of −

  • Modules
  • Functions
  • Variables
  • Statements and Expressions
  • Comments

Your First TypeScript Code

Let us start with the traditional “Hello World” example −

var message:string = "Hello World" 
console.log(message)

On compiling, it will generate following JavaScript code.

//Generated by typescript 1.8.10
var message = "Hello World";
console.log(message);
  • Line 1 declares a variable by the name message. Variables are a mechanism to store values in a program.

  • Line 2 prints the variable’s value to the prompt. Here, console refers to the terminal window. The function log () is used to display text on the screen.

Compile and Execute a TypeScript Program

Let us see how to compile and execute a TypeScript program using Visual Studio Code. Follow the steps given below −

Step 1 − Save the file with .ts extension. We shall save the file as Test.ts. The code editor marks errors in the code, if any, while you save it.

Step 2 − Right-click the TypeScript file under the Working Files option in VS Code’s Explore Pane. Select Open in Command Prompt option.

Compile and Execute

Step 3 − To compile the file use the following command on the terminal window.

tsc Test.ts

Step 4 − The file is compiled to Test.js. To run the program written, type the following in the terminal.

node Test.js

Compiler Flags

Compiler flags enable you to change the behavior of the compiler during compilation. Each compiler flag exposes a setting that allows you to change how the compiler behaves.

The following table lists some common flags associated with the TSC compiler. A typical command-line usage uses some or all switches.

S.No. Compiler flag & Description
1.

--help

Displays the help manual

2.

--module

Load external modules

3.

--target

Set the target ECMA version

4.

--declaration

Generates an additional .d.ts file

5.

--removeComments

Removes all comments from the output file

6.

--out

Compile multiple files into a single output file

7.

--sourcemap

Generate a sourcemap (.map) files

8.

--module noImplicitAny

Disallows the compiler from inferring the any type

9.

--watch

Watch for file changes and recompile them on the fly

Note − Multiple files can be compiled at once.

tsc file1.ts, file2.ts, file3.ts

Identifiers in TypeScript

Identifiers are names given to elements in a program like variables, functions etc. The rules for identifiers are −

  • Identifiers can include both, characters and digits. However, the identifier cannot begin with a digit.

  • Identifiers cannot include special symbols except for underscore (_) or a dollar sign ($).

  • Identifiers cannot be keywords.

  • They must be unique.

  • Identifiers are case-sensitive.

  • Identifiers cannot contain spaces.

The following tables lists a few examples of valid and invalid identifiers −

Valid identifiers Invalid identifiers
firstName Var
first_name first name
num1 first-name
$result 1number

TypeScript ─ Keywords

Keywords have a special meaning in the context of a language. The following table lists some keywords in TypeScript.

break as any switch
case if throw else
var number string get
module type instanceof typeof
public private enum export
finally for while void
null super this new
in return true false
any extends static let
package implements interface function
new try yield const
continue do catch

Whitespace and Line Breaks

TypeScript ignores spaces, tabs, and newlines that appear in programs. You can use spaces, tabs, and newlines freely in your program and you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand.

TypeScript is Case-sensitive

TypeScript is case-sensitive. This means that TypeScript differentiates between uppercase and lowercase characters.

Semicolons are optional

Each line of instruction is called a statement. Semicolons are optional in TypeScript.

Example

console.log("hello world")
console.log("We are learning TypeScript")

A single line can contain multiple statements. However, these statements must be separated by a semicolon.

Comments in TypeScript

Comments are a way to improve the readability of a program. Comments can be used to include additional information about a program like author of the code, hints about a function/ construct etc. Comments are ignored by the compiler.

TypeScript supports the following types of comments −

  • Single-line comments ( // ) − Any text between a // and the end of a line is treated as a comment

  • Multi-line comments (/* */) − These comments may span multiple lines.

Example

//this is single line comment 
 
/* This is a  
   Multi-line comment 
*/

TypeScript and Object Orientation

TypeScript is Object-Oriented JavaScript. Object Orientation is a software development paradigm that follows real-world modelling. Object Orientation considers a program as a collection of objects that communicate with each other via mechanism called methods. TypeScript supports these object oriented components too.

  • Object − An object is a real time representation of any entity. According to Grady Brooch, every object must have three features −

    • State − described by the attributes of an object

    • Behavior − describes how the object will act

    • Identity − a unique value that distinguishes an object from a set of similar such objects.

  • Class − A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object.

  • Method − Methods facilitate communication between objects.

Example: TypeScript and Object Orientation

class Greeting { 
   greet():void { 
      console.log("Hello World!!!") 
   } 
} 
var obj = new Greeting(); 
obj.greet();

The above example defines a class Greeting. The class has a method greet (). The method prints the string “Hello World” on the terminal. The new keyword creates an object of the class (obj). The object invokes the method greet ().

On compiling, it will generate following JavaScript code.

//Generated by typescript 1.8.10
var Greeting = (function () {
   function Greeting() {
   }
   Greeting.prototype.greet = function () {
      console.log("Hello World!!!");
   };
	return Greeting;
}());

var obj = new Greeting();
obj.greet()

The output of the above program is given below −

Hello World!!!


Advertisements
E-Books Store