TypeScript Basic Syntax: TypeScript Tutorial for Beginners

What is the syntax of TypeScript?

TypeScript Syntax establishes the guidelines for constructing programs. Each language specification has its own unique syntax.

Let’s take a look at the example below:

var greetings:string = "Hi, Welcome to Itsourcecode!" 
console.log(greetings)

The first line introduces a variable named “greetings”. Variables serve as containers for storing data values in a program.

The second line outputs the value of the variable to the console. In this context, ‘console’ refers to the terminal window.

The function “log()” is utilized to display text on the screen.

Output:

Hi, Welcome to Itsourcecode!

The components of a TypeScript program include:

  1. Modules
// sampleModule.ts
export function greet(name: string): string {
  return `Hi, welcome to ${website}!`;
}

Aside from that, you can import this module in another file like this:

// app.ts
import { greet } from './sampleModule';
console.log(greet('`Hi, welcome to Itsourcecode'));

  1. Functions
function add(x: number, y: number): number {
  return x + y;
}
console.log(add(100, 200)); 

  1. Variables
let grade: number = 90;
let student: string = "Itsourcecode";
let isStudent: boolean = true;
let grades: number[] = [90, 85, 95];

  1. Statements and Expressions
// Statement
let x: number = 20;

// Expression
let y: number = x * 5;

Every individual instruction in TypeScript is referred to as a statement.

The use of semicolons in TypeScript is not mandatory.

  1. Comments

Comments make code easier to understand. They can add extra details like who wrote the code or tips about how a part of the code works. The compiler doesn’t pay attention to comments.

// This is a single line comment

/*
This is a
multi-line comment
*/

  1. Classes

Classes in TypeScript allow you to create blueprints for objects.

class Person {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
}

  1. Control Flow Statements

if-else and switch statements for conditional execution are supported by TypeScript.

let age: number = 18;
if (age > 0) {
    console.log("Positive number");
} else {
    console.log("Negative number");
}

  1. Loops

for, while, and do-while loops for iteration are supported by TypeScript.

for (let i = 0; i < 10; i++) {
console.log(i);
}

  1. Intersection Types

Intersection types allow you to multiple types into one.

type Person = {
    name: string;
};

type Employee = {
    id: number;
};

type EmployeePerson = Person & Employee;

  1. Union Types

Union types allow a variable to have multiple types.

let result: number | string;
result = 90;
result = "Pass";

  1. Type Guards

Type guards allow narrowing down the type of a variable within a conditional block.

function isString(value: any): value is string {
return typeof value === "string";
}

  1. Type Aliases

Type aliases allow you to creat custom names for types.

type UserID = string;
let id: UserID = "Itsc143";

Keywords in TypeScript

Here are some of the keywords in TypeScript:

Reserved words:

breakcasecatchclass
constcontinuedebuggerdefault
deletedoelseenum
exportextendsfalsefinally
forfunctionifimport
ininstanceOfnewnull
returnsuperswitchthis
throwtruetrytypeOf
varvoidwhilewith

Strict Mode Reserved Words:

asimplementsinterfacelet
packageprivateprotectedpublic
staticyield

TypeScript Identifiers

TypeScript Identifiers are the names assigned to elements such as variables, functions, and so on.

The guidelines for identifiers are as follows:

📌 Identifiers can comprise both letters and numbers, but they cannot start with a number.

📌 Special symbols are not allowed in identifiers, with the exception of the underscore (_) and the dollar sign ($).

📌 Keywords cannot be used as identifiers.

📌 Each identifier must be unique.

📌TypeScript Identifiers are case-sensitive.

📌 Spaces are not permitted in identifiers

Here are some examples of valid and invalid identifiers in TypeScript:

Valid Identifiers:

  • userName
  • user_name
  • num1
  • $result
  • _temp

Invalid Identifiers:

  • 123abc (Identifiers cannot start with a number)
  • user name (Identifiers cannot contain spaces)
  • user-name (Hyphen is not allowed in identifiers)
  • let (Identifiers cannot be keywords)
  • @name (Special characters, except for underscore (_) and dollar sign ($), are not allowed)

Conclusion

In conclusion, TypeScript is a high-level programming language developed by Microsoft, extending JavaScript with optional static typing and other features.

Its syntax encompasses various elements such as modules, functions, variables, statements, comments, classes, control flow statements, loops, and type definitions.

I hope this article helps you in understanding the TypeScript Basic Syntax. If you have questions or inquiries just leave a comment below.

Leave a Comment