Welcome to these comprehensive TypeScript tutorials! Whether you’re just starting out or looking to deepen your understanding, you’re in the right place. In this tutorial, I will help you learn TypeScript, a powerful superset of JavaScript that brings static typing and other advanced features to the table. We’ll walk through the basics, set up your environment, and write your first TypeScript program together. By the end of this guide, you’ll have a solid grasp of TypeScript and be ready to use it in your projects.
What is TypeScript?
TypeScript is a superset of JavaScript, meaning it builds on JavaScript by adding new features and capabilities. It was developed by Microsoft to address some of JavaScript’s limitations, particularly in large-scale applications.
One of the key features of TypeScript is static typing, which allows developers to catch errors at compile time rather than at runtime, making code more robust and maintainable.
Check out
- TypeScript Program to Print Hello World
- TypeScript Single vs Double Quotes
- Is TypeScript Frontend or Backend?
- Differences Between TypeScript and JavaScript
- Differences Between Type and Interface in TypeScript
- Difference Between void and undefined in TypeScript
- Difference Between boolean and Boolean in TypeScript
- Difference Between String and string in TypeScript
- Difference Between Let vs Const in TypeScript
- Difference Between Record vs Object in TypeScript
- Difference Between Protected vs Private in TypeScript
- Check if an Object is a String in TypeScript
- Loose vs Strict Equality in TypeScript
- Difference Between Undefined and Null In TypeScript
- Check if an Object is Empty in TypeScript
- TypeScript Class vs Interface
- Check If a Key Exists in a TypeScript Object
- Check Types in TypeScript
- Check If a Variable is Undefined in TypeScript
- TypeScript let vs var Difference
- Type vs Interface in TypeScript
- TypeScript: Check If a Key Exists in a Object
- Iterate Over Objects in TypeScript
- Convert TypeScript Objects to JSON
- Index Signature in TypeScript
- Difference Between Namespaces and Modules in TypeScript
- Define and Use an Empty Object Type in TypeScript
- TypeScript vs JavaScript for React Development
- Deep Clone an Object in TypeScript
- TypeScript keyof Operator
- Exception Handling in TypeScript
- TypeScript Generic Object Types
- TypeScript Classes: Concepts, Syntax, and Examples
- Function Overloading in TypeScript
- TypeScript Type Casting
- Ternary Operator in TypeScript
- Spread Operator in TypeScript
- Initialize Maps in TypeScript
- TypeScript Type Narrowing
- TypeScript Constructor Overloading
- Use Typescript Omit with Multiple Properties
- Call REST APIs Using TypeScript
- TypeScript Decorators
- Use Non-Null Assertion (!) in TypeScript
- TypeScript As Keyword
- TypeScript Promises
- Use Comments in TypeScript
- How to Ignore Lines in TypeScript?
- Check and Print the Type of an Object in TypeScript
- Difference Between TypeScript .ts and .tsx Files
- Use of Any Type in TypeScript
- Implement Sleep Function in TypeScript
- Cannot Find Module TypeScript
- TypeScript vs React
- Use ForwardRef in TypeScript
- TypeScript Event Types
- React’s useContext Hook with TypeScript
- TypeScript Best Practices
Why Use TypeScript?
Here are a few reasons why we use TypeScript.
- Static Typing: TypeScript allows you to define types for variables, function parameters, and return values, catching type-related errors early.
- Enhanced IDE Support: TypeScript provides better autocompletion, navigation, and refactoring support in modern IDEs like Visual Studio Code.
- Improved Code Quality: TypeScript’s type system helps you write cleaner and more predictable code.
- Compatibility: TypeScript code compiles to plain JavaScript, making it compatible with any JavaScript environment.
Check out How to Use Try Catch in TypeScript? and How to Handle Catch Error Types in TypeScript?
Set Up Your TypeScript Environment
Now, let me explain how to set up the TypeScript environment step by step.
Step 1: Install Node.js and npm
To get started with TypeScript, you must install Node.js and npm (Node Package Manager) on your machine. You can download and install them from the official Node.js website.
Step 2: Install TypeScript
Once you have Node.js and npm installed, you can install TypeScript globally on your machine by running the following command in your terminal:
npm install -g typescriptStep 3: Verify Installation
To verify that TypeScript is installed correctly, you can check the version by running:
tsc --versionIf everything is set up correctly, you should see the version number of TypeScript.
Step 4: Set Up Visual Studio Code
Visual Studio Code (VSCode) is a popular code editor that supports TypeScript. You can download it from the official VSCode website. Once installed, you can enhance your TypeScript development experience by installing the TypeScript extension from the VSCode marketplace.
This is so simple to set up the TypeScript environment for development.
Write Your First TypeScript Program
Now, in the next step to learn as a beginner, you should know how to write your first TypeScript program.
Follow the below steps.
Step 1: Create a New Project
Create a new directory for your TypeScript project and navigate into it:
mkdir my-typescript-project
cd my-typescript-projectStep 2: Initialize a TypeScript Project
Initialize a new TypeScript project by running:
tsc --initThis command generates a tsconfig.json file, which contains configuration options for the TypeScript compiler.
Step 3: Create a TypeScript File
Create a new file named index.ts in your project directory:
touch index.tsStep 4: Write TypeScript Code
Open index.ts in your code editor and write the following code:
function greet(name: string): string {
return `Hello, ${name}!`;
}
let userName: string = "John";
console.log(greet(userName));In this example, we define a greet function that takes a name parameter of type string and returns a greeting message. We then declare a variable userName of type string and call the greet function with userName as the argument.
Step 5: Compile TypeScript to JavaScript
To compile your TypeScript code to JavaScript, run the following command in your terminal:
tscThis command compiles all .ts files in your project according to the settings in tsconfig.json. By default, it generates a corresponding .js file for each .ts file.
Step 6: Run the Compiled JavaScript
You can now run the compiled JavaScript file using Node.js:
node index.jsYou should see the output:
Hello, John!Check out
Basic Types in TypeScript
TypeScript enhances JavaScript by adding static types, which allows you to explicitly declare the types of variables, function parameters, and return values. This helps catch errors early during development and makes the code more readable and maintainable. Let’s dive deeper into the basic types available in TypeScript with detailed explanations and examples.
Number
The number type in TypeScript is used to represent both integer and floating-point values. It supports decimal, hexadecimal, binary, and octal literals.
Example
let age: number = 30; // Decimal
let hex: number = 0x1a; // Hexadecimal
let binary: number = 0b1010; // Binary
let octal: number = 0o23; // Octal
console.log(age); // 30
console.log(hex); // 26
console.log(binary); // 10
console.log(octal); // 19
String
The string type is used to represent textual data. You can use single quotes ('), double quotes ("), or backticks (`) for string literals. Backticks allow for template strings, which can include embedded expressions.
Example
let firstName: string = "Jane";
let lastName: string = 'Doe';
let fullName: string = `${firstName} ${lastName}`;
console.log(firstName); // Jane
console.log(lastName); // Doe
console.log(fullName); // Jane Doe
Boolean
The boolean type represents logical values: true or false.
Example
let isStudent: boolean = true;
let hasGraduated: boolean = false;
console.log(isStudent); // true
console.log(hasGraduated); // false
Array
The array type can be declared in two ways: using the type followed by [], or using the generic Array<type> syntax.
Example
let hobbies: string[] = ["Reading", "Traveling", "Cooking"];
let scores: Array<number> = [95, 88, 76];
console.log(hobbies); // ["Reading", "Traveling", "Cooking"]
console.log(scores); // [95, 88, 76]
Tuple
A tuple type allows you to express an array with a fixed number of elements whose types are known but can be different.
Example
let person: [string, number] = ["John", 25];
console.log(person); // ["John", 25]
console.log(person[0]); // John
console.log(person[1]); // 25
Enum
Enums allow you to define a set of named constants. TypeScript provides both numeric and string-based enums.
Example
enum Color {
Red,
Green,
Blue
}
let favoriteColor: Color = Color.Green;
console.log(favoriteColor); // 1 (since enums are zero-based by default)
console.log(Color[1]); // Green
// String Enum
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT"
}
let move: Direction = Direction.Up;
console.log(move); // UPAny
The any type is a powerful way to work with existing JavaScript. It allows you to opt out of type checking for a variable.
Example
let randomValue: any = "Hello";
randomValue = 42;
randomValue = true;
console.log(randomValue); // trueVoid
The void type is used to indicate that a function does not return a value.
Example
function logMessage(message: string): void {
console.log(message);
}
logMessage("This is a message."); // This is a message.Null and Undefined
TypeScript has two special types, null and undefined, which have their own types respectively. By default, null and undefined are subtypes of all other types.
Example
let u: undefined = undefined;
let n: null = null;
console.log(u); // undefined
console.log(n); // nullNever
The never type represents the type of values that never occur. For instance, a function that always throws an error or a function that never returns.
Example
function throwError(message: string): never {
throw new Error(message);
}
function infiniteLoop(): never {
while (true) {}
}Object
The object type represents non-primitive types, i.e., anything that is not number, string, boolean, symbol, null, or undefined.
Example
let person: object = { name: "John", age: 25 };
console.log(person); // { name: "John", age: 25 }Working with Interfaces
Interfaces in TypeScript allow you to define the structure of an object. They provide a way to enforce the shape of an object and ensure that it has the required properties.
Example
interface Person {
firstName: string;
lastName: string;
age: number;
greet(): string;
}
let person: Person = {
firstName: "Alice",
lastName: "Johnson",
age: 28,
greet: function (): string {
return `Hello, my name is ${this.firstName} ${this.lastName}.`;
}
};
console.log(person.greet());In this example, we define an interface Person with properties firstName, lastName, age, and a method greet. We then create an object person that adheres to the Person interface.
- How to Set Default Values in TypeScript Interfaces?
- How to Choose Between TypeScript Classes and Interfaces?
- How to Convert JSON to TypeScript Interface?
- How to Create an Object from an Interface in TypeScript?
- Optional Parameters in TypeScript Interfaces
- Loose vs Strict Equality in TypeScript
- Require vs Import in TypeScript
- Unknown vs Any in TypeScript
- TypeScript Objects With Advanced Type Safety
- TypeScript Switch Statements
- Use TypeScript Environment Variables
- TypeScript Global Variables
- Master TypeScript Enum Naming Conventions
- TypeScript vs Node.js
Advanced TypeScript Features
Generics
Generics allow you to create reusable components that can work with a variety of types. They provide a way to create functions, classes, and interfaces that can operate on different types without sacrificing type safety.
Example
function identity<T>(arg: T): T {
return arg;
}
let output1 = identity<string>("Hello");
let output2 = identity<number>(42);In this example, we define a generic function identity that takes an argument of type T and returns a value of the same type. We then call the function with different types.
Modules
Modules in TypeScript allow you to organize your code into reusable and maintainable pieces. You can export and import classes, interfaces, functions, and variables from one module to another.
Example
// math.ts
export function add(a: number, b: number): number {
return a + b;
}
// main.ts
import { add } from './math';
console.log(add(5, 3));In this example, we define a function add in a module math.ts and export it. We then import the add function in main.ts and use it.
TypeScript Tutorials for Beginners
Here is the list of TypeScript tutorials for beginners.
- How to Use the Exclamation Mark in TypeScript?
- Difference Between == and === in TypeScript
- How to Use the Double Question Mark (??) Operator in TypeScript?
- Property Does Not Exist on Type Error in TypeScript
- How to Check the Type of a Variable in TypeScript?
- How to Set Default Values for TypeScript Types?
- Define and Use TypeScript Interface Array of Objects
- How to Use TypeScript Interface Function Properties?
- How to Check if an Object is Type of Interface in TypeScript?
- 101 Best TypeScript Interview Questions and Answers for Experienced Professionals
- How to Check if an Object Implements an Interface in TypeScript?
- How to Remove a Property from an Object in TypeScript?
- How to Extend Interfaces with Classes in TypeScript?
- Nullish Coalescing (??) vs Logical OR (||) Operator in TypeScript
- TypeScript Record vs Object
- Conditionally Add Property to Object in TypeScript
- Check If Object Is Undefined in TypeScript
- Check if an Object Has a Property in TypeScript
- Mapped Types in TypeScript
- Typescript Iterate Over Records
Conclusion
By following this step-by-step guide, I hope you have learned how to set up a TypeScript environment, write and compile TypeScript code, and use some of the basic and advanced features of TypeScript. I hope this tutorial helps you to start with TypeScript as a beginner.
TypeScript Control Statement Tutorials
Here is the list of TypeScript control statement tutorials:
- For Loop in TypeScript
- How to Get Index in forEach Loop in TypeScript?
- for…in Loops in TypeScript
- How to Use for…of Loops in TypeScript?
- TypeScript forEach Loop with Index
- How to Break Out of a forEach Loop in TypeScript?
- How to Break Out of Loops in TypeScript?
- Do-While Loop in TypeScript
- How to Use the Break Statement in TypeScript For Loops?
- How to Use For Loop Range in TypeScript?
- How to Use TypeScript Loops to Execute Code Multiple Times?
- Error TS2550: Property ‘includes’ Does Not Exist on Type ‘String’ in TypeScript
- Difference Between Record vs Map in TypeScript
- Check for an Empty Object in TypeScript
- TypeScript Classes: Concepts, Syntax, and Examples
- Understanding TypeScript’s ‘satisfies’ Operator
- Understanding satisfies vs as Operator in TypeScript
- Loop Through Objects in TypeScript
- Show Alerts in TypeScript
- Merge Objects in TypeScript
- Why Use TypeScript? Top 10 Benefits for Modern Web Development
- TypeScript Exception Handling
- Implement Queues in TypeScript
- 100 TypeScript Interview Questions And Answers