Blog Details
Md Ferdows Ohid Anu
18 Oct 2024
5 min read
TypeScript, a programming language developed by Microsoft, is a superset of JavaScript. This means that any valid JavaScript code is also valid TypeScript code. However, TypeScript introduces static typing, a feature that allows you to define the data types of variables, functions, and properties. This can lead to more robust, maintainable, and error-free code.
TypeScript introduces a rich type system that allows you to define the expected values of variables, functions, and properties. Here are some of the most common basic types:
Numbers:
let age: number = 30;
let pi: number = 3.14159;
Strings:
let name: string = "Alice";
let message: string = "Hello, world!";
Booleans:
let isLoggedIn: boolean = true;
let hasError: boolean = false;
Arrays:
let numbers: number[] = [1, 2, 3];
let fruits: string[] = ["apple", "banana", "orange"];
Objects:
let person: { name: string; age: number; } = {
name: "Bob",
age: 25
};
One of the powerful features of TypeScript is its ability to infer types automatically. This means that in many cases, you don't need to explicitly specify the type of a variable. TypeScript will infer the type based on the value assigned to it.
let x = 10; // TypeScript infers the type of x as number
let y = "Hello"; // TypeScript infers the type of y as string
Note: While type inference is convenient, explicitly specifying types is often good practice, especially for complex data structures or when you want to enforce a particular type.
To get started with TypeScript, you can use a TypeScript compiler or a development environment that supports TypeScript, such as Visual Studio Code. You can also use tools like tsc
to compile your TypeScript code into JavaScript.
// app.ts
function greet(name: string): string {
return "Hello, " + name + "!";
}
let user: string = "John";
let message: string = greet(user);
console.log(message);
To compile this code, you can run the following command in your terminal:
tsc app.ts
This will generate a app.js
file containing the compiled JavaScript code.
TypeScript is a powerful language that can help you write cleaner, more maintainable, and more reliable code. By understanding its basic types, type inference, and more complex features, you can effectively leverage TypeScript in your projects.
Don’t worry, we don’t spam!