TypeScript Syntax for Programming

We offer you a brighter future with industry-ready online courses - Start Now!!

In the previous article, we learned how to download, install and run a TypeScript file on the local machine. The first and primary step to learning any programming language is to learn its basic data types. Data types can also be considered the building blocks of any programming language. This article will dive deep into the basic TypeScript data types and syntax learn more about the language.

Basic TypeScript Syntax

1. Variables and Types

In TypeScript, we can declare variables using the let or const keyword. The let keyword is used to declare variables that can be reassigned, while the const keyword is used to declare variables that cannot be reassigned.

let firstName: string = 'DataFlair';
const age: number = 20;

In the example above, we declared a variable firstName of type string and assigned it “DataFlair.” We also declared a variable age of type number and assigned it 20. The type annotations in TypeScript are optional, but they can help catch errors early in development.

Syntax for some of the datatypes are as follows –

a. Number

The number type represents both integer and floating-point numbers in TypeScript. The number type supports all arithmetic operations and methods that are available in JavaScript.

For example:

let DataFlair_num1: number = 10; // an integer
let DataFlair_num2: number = 10.5; // a floating-point number

b. String

The string type represents textual data in TypeScript. The string type supports all string manipulation methods that are available in JavaScript.

For example:

let DataFlair_str1: string = 'Hello, world!';
let DataFlair_str2: string = 'Single quotes are also valid.';

c. Boolean

The boolean type represents true or false values in TypeScript. The boolean type is commonly used for conditional statements and logical operations.

For example:

let DataFlair_isDone: boolean = false;
let DataFlair_hasStarted: boolean = true;

d. Array

The array type represents a collection of values of the same type in TypeScript. Arrays in TypeScript can be declared using the square bracket syntax, or using the Array<> generic type.

For example:

let DataFlair_arr1: number[] = [1, 2, 3];
let DataFlair_arr2: Array<string> = ['apple', 'banana', 'cherry'];

2. Functions

In TypeScript, we can declare functions using the function keyword. We can also specify the types of the function parameters and return values using type annotations.

function DataFlair_add(x: number, y: number) {
 return x + y;
}

In the example above, we declared a function add that takes two parameters of the type number and returns a value of the type number.

3. Classes

In TypeScript, we can declare classes using the class keyword. We can also use the constructor method to initialize the class properties.

class DataFlair_Person {
 firstName: string;
 lastName: string;
 age: number;


 constructor(firstName: string, lastName: string, age: number) {
   this.firstName = firstName;
   this.lastName = lastName;
   this.age = age;
 }


 getFullName(): string {
   return `${this.firstName} ${this.lastName}`;
 }
}

In the example above, we declared a class DataFlair_Person with three properties: firstName, lastName, and age. We also declared a constructor method that takes three parameters and initializes the class properties. We also declared a method getFullName that returns the person’s full name.

4. Interfaces

In TypeScript, we can declare interfaces to define the shape of an object. We can use interfaces to enforce a certain structure of an object.

interface DataFlair_Person {
 firstName: string;
 lastName: string;
 age: number;
}

In the example above, we declared an interface DataFlair_Person that defines the shape of a person object. The DataFlair_Person interface has three properties: firstName, lastName, and age.

5. Type Aliases

In TypeScript, we can use type aliases to create a new name for a type. This can be useful to simplify complex type annotations.

type DataFlair_FullName = string;
type DataFlair_Age = number;

In the example above, we created two type aliases: DataFlair_FullName and DataFlair_Age. The DataFlair_FullName alias defines a string representing a person’s full name, and the DataFlair_Age alias defines a number representing a person’s age.

6. Enums

In TypeScript, we can use enums to define a set of named constants. We can use enums to improve the readability and maintainability of our code.

enum DataFlair_Direction {
 Up,
 Down,
 Left,
 Right,
}

In the example above, we declared an enum DataFlair_Direction that defines a set of named constants. The DataFlair_Direction enum has four constants: Up, Down, Left, and Right. Each constant is assigned a numeric value starting from 0.

7. Generics

In TypeScript, we can use generics to create reusable code. Generics allow us to define functions and classes that can work with various data types.

function DataFlair_reverse<T>(list: T[]): T[] {
 return list.reverse();
}

In the example above, we declared a generic function DataFlair_reverse that takes an array of type T and returns an array of type T. The T type parameter allows the function to work with any data type.

8. Modules

Modules are used to organize code into reusable and maintainable units. In TypeScript, modules can be defined using the import and export keywords. The import keyword is used to import code from another module, and the export keyword is used to expose code to other modules.

Example:

import { DataFlair_add } from './math';
console.log(DataFlair_add(2, 3)); // outputs 5

9. Comments

Comments are used to document code and make it more understandable for other developers. In TypeScript, there are two types of comments: single-line comments and multi-line comments. Single-line comments start with //, and multi-line comments start with /* and end with */.

// This is a single-line comment


/*
This is a multi-line comment
that spans multiple lines.
*/

10. Expressions and Statements

An expression combines one or more values, operators, and/or function calls that return a value when evaluated. For example, 2 + 3 is an expression that evaluates to 5. Another example of an expression is Math.max(10, 20), which returns the maximum value of its arguments.

A statement, on the other hand, is a command that performs a specific action. Statements include assignments, loops, conditionals, and function calls. Unlike expressions, statements do not return a value when executed. For example, let x = 5; is a statement that assigns the value 5 to the variable x. Another example of a statement is if (x > 0) { console.log(“Positive”); }, which checks if the value of x is greater than 0 and logs the message “Positive” if it is.

Example:

Expression:

const DataFlairsum = 2 + 3;

Statement:

let DataFlair_x = 0;
if (DataFlair_x === 0) {
 console.log('DataFlair_x is zero');
}

11. Flags

Flags in TypeScript are special options that can be passed to the TypeScript compiler to modify its behavior. These flags are used to control the output format, enable or disable certain features, and optimize the compilation process. Some common flags in TypeScript include:

1. –target: Specifies the ECMAScript target version for the generated JavaScript code. The available options include es3, es5, es6, es2015, es2016, es2017, es2018, es2019, es2020, and es2021.

2. –module: Specifies the module format for the generated JavaScript code. The available options include commonjs, amd, system, umd, es2015, and es2020.

3. –strict: Enables strict type checking in TypeScript. This flag enables several other options, including –noImplicitAny, –strictNullChecks, –strictFunctionTypes, –strictPropertyInitialization, and –noImplicitThis.

4. –noEmit: Disables the generation of JavaScript code by the TypeScript compiler. This flag is useful for performing type checking without generating any output.

5. –watch: Enables the TypeScript compiler to watch for changes in the source files and automatically recompile them when necessary.

Overall, flags in TypeScript are powerful tools that can be used to customize the compiler’s behavior and optimize the development process.

Keywords in TypeScript

Keywords are fundamental to any programming language, and TypeScript is no exception. In TypeScript, keywords play an essential role in defining the syntax and structure of the language. Understanding these keywords is critical to writing correct and maintainable TypeScript code.

Here are some of the most important keywords in TypeScript:

1. var, let, const

Variables are used to store data values in a program. In TypeScript, you can declare variables using the var, let, and const keywords. The var keyword declares a variable that is scoped to the nearest function or global context. The let keyword is used to declare a block-scoped variable, and the const keyword is used to declare a read-only variable.

Example:

var DataFlair_a = 10; // function-scoped variable
let DataFlair_b = 20; // block-scoped variable
const DataFlair_c = 30; // read-only variable

2. function

Functions encapsulate a block of code that can be executed repeatedly with different inputs. In TypeScript, you can define functions using the function keyword. Functions can take parameters, and they can also return values.

Example:

function DataFlair_add(a: number, b: number): number {
 return a + b;
}

3. class

Classes are used to define object blueprints that encapsulate data and behavior. In TypeScript, you can define classes using the class keyword. Classes can have properties and methods and can be extended to create new classes.

Example:

class DataFlair_Person {
 name: string;
 age: number;


 constructor(name: string, age: number) {
   this.name = name;
   this.age = age;
 }


 sayHello() {
   console.log(
     `Hello, my name is ${this.name} and I am ${this.age} years old.`
   );
 }
}

4. interface

Interfaces are used to define contracts for object structures. In TypeScript, you can define interfaces using the interface keyword. Interfaces define properties and methods an object must implement to satisfy the contract.

Example:

interface DataFlair_Person {
 name: string;
 age: number;
 sayHello(): void;
}

These are just a few of the most important keywords in TypeScript. There are many more, such as enum, type, import, export, and more. Understanding how these keywords work together is key to mastering TypeScript and building robust applications.

Conclusion

In this article, we covered the basic syntax of TypeScript. We explored how to declare variables and types, functions, classes, interfaces, type aliases, enums, and generics in TypeScript. TypeScript provides many features that can improve JavaScript code’s scalability, maintainability, and robustness. With TypeScript, we can catch errors early in development and create more reliable applications.

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

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