TypeScript Syntax

In the last tutorial, we learned how to create a simple Hello World example using TypeScript. Before going further, we need to learn the Typescript Syntax and basic rules that need to be followed while writing code in TypeScript.

TypeScript is Case-sensitive

TypeScript is case sensitive. This means that foo is not the same as Foo.

Typescript Statements

A Typescript statement is an instruction to perform a specific action. A Typical Typescript program consists of several such sequences of statements and they control the flow of the program.

Here is an example of three statements

//statement 1  create a variable
var message;      

//statement 2  assigns “Hello World” to message variable
message=”hello world”; 
       
//statmenent 3 print out console log
console.log(message);

A single statement may span multiple lines.

Or you can write multiple statements in a single line, provided you separate each statement by a semicolon.

Semi-Colon

; the semicolon is used to indicate the end of a statement.

For Example

var message;
message=”hello world”;
console.log(message);

But, they are optional if you use a single line for each statement

For Example, this is also valid

var message
message=”hello world”
console.log(message)

But, they are required if you have multiple statements in a line

For Example

var message ; message=”hello world” ; console.log(message) ;

TypeScript Expressions

Expressions are units of code that produces value. They can appear anywhere in the code. They can be part of the function arguments or right side of an assignment, etc

Example of Expressions

5+7           //This is an arithmetic expression that evaluates to 12
I++           //Arithmetic expression
'Something'   //Primary Expressions
a && b        // Logical Expressions

The expressions can be of various types Arithmetic, String, Primary, Array & object Initialisation, Logical, Left-Hand side. Property access, object Creation, Function definition, invocation, etc.

Whitespace and Line Breaks

You can add spaces, tabs, and newline characters anywhere in the Typescript Program. The Compiler will ignore them. You can use them to indent your code so that it very easily readable.

Comments in TypeScript

The Comments can be applied to the line of code or to a block of code

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

Example

//this is a single-line comment 

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

Example

/* This is a  
    Multi-line comment 
*/

Summary

In this tutorial, we learned a few of the basic Typescript syntax rules that need to be followed.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top