TypeScript is an open-source programming language developed by Microsoft that extends JavaScript by adding optional static typing to the language. It aims to make JavaScript development more scalable and maintainable, especially for large-scale projects. TypeScript code is transpiled into JavaScript code, making it compatible with all modern browsers and JavaScript frameworks.
TypeScript Basics
TypeScript any Type:
The any type in TypeScript allows variables to hold values of any data type. It is often used when the type of a variable is not known during development or when interfacing with JavaScript libraries that have dynamic typing.
Syntax:
let value: any;
TypeScript union type:
Union types allow a variable to hold values of multiple types. For example, number | string denotes a variable that can be either a number or a string.
Syntax:
let Variable_name: data_type1 | data_type2
Example:
function display(value: number | string) {
if (typeof value === "number") {
console.log("The value is a number:", value);
} else {
console.log("The value is a string:", value.toUpperCase());
}
}
display(22); // Output: The value is a number: 22
display("gfg"); // Output: The value is a string: GFG
Type aliases:
Type aliases allow developers to create custom names for existing types, making complex types more readable and easier to maintain.
Syntax:
type type_name = create_your_type;
Example:
type Point = { x: number; y: number };
const point: Point = { x: 10, y: 20 };
console.log(point); // Output: { x: 10, y: 20 }
interface:
Interfaces define the structure of an object in TypeScript. They can include properties, methods, and optional members. Interfaces are commonly used for defining contracts within the codebase
Syntax:
interface Name_of_interface{
key : value,
key : value
}
Example:
interface Person {
name: string;
age: number;
}
function greet(person: Person): string {
return `Hello, ${person.name}!`;
}
const user: Person = { name: "GFG", age: 22 };
console.log(greet(user)); // Output: Hello, GFG!
Enums:
Enums (short for enumerations) allow developers to define a set of named constants. Enums are useful for representing a fixed set of values within the codebase.
Syntax:
enum nafe_of_enum{
value1,
value2,
.
.
.
value_n
}
Example:
enum DayOfWeek {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
function getDayName(day: DayOfWeek): string {
return DayOfWeek[day];
}
console.log(getDayName(DayOfWeek.Monday)); // Output: Monday
Example 1: This example shows the use of Type Guards with Arrays.
// Define a type guard function
function isNumberArray(arr: any[]):
arr is number[] {
return arr.every(item => typeof item === "number");
}
// Use the type guard in a conditional statement
function sumOrJoin(arr: number[] |
string[]): number | string {
if (isNumberArray(arr)) {
return arr.reduce((acc, curr) =>
acc + curr, 0);
} else {
return arr.join(", ");
}
}
console.log(sumOrJoin([1, 2, 3]));
console.log(sumOrJoin(["hello", "world"]));
Output:
6
hello, world
Example 2: This example shows the use of Type Guards with Objects.
// Define a type guard function
function isPerson(obj: any): obj is
{ name: string; age: number } {
return typeof obj === "object" &&
"name" in obj && "age" in obj;
}
// Use the type guard in a conditional statement
function greet(obj: {
name: string;
age: number
} | string): string {
if (isPerson(obj)) {
return `Hello, ${obj.name}!`;
} else {
return `Hello, ${obj}!`;
}
}
console.log(greet({ name: "Gfg", age: 22 }));
console.log(greet("world"));
Output:
Hello, Gfg!
Hello, world!
Steps to Run the Code
- Step1: Install Node.js from official website.
- Step2: Install TypeScript globally by running npm install -g typescript in your terminal.
- Step3: Copy the code examples into separate TypeScript files (.ts extension).
- Step4: Compile the TypeScript files into JavaScript using the TypeScript compiler (tsc) by running tsc filename.ts.
- Step5: Run the generated JavaScript files using Node.js or include them in an HTML file for browser execution.
Advantages of Using TypeScript
- Static Typing: TypeScript provides type safety, catching errors at compile time and improving code quality.
- Enhanced Tooling: TypeScript offers better IDE support with features like code completion, refactoring tools and inline documentation.
- Code Maintainability: By enforcing type safety and providing clearer interfaces, TypeScript enhances code maintainability and readability.
How to Use TypeScript in a Project?
- Create a new TypeScript file with the .ts extension.
- Write your TypeScript code as usual.
- TypeScript allows you to gradually adopt static typing by adding type annotations where needed.
- Compile the TypeScript code into JavaScript using the TypeScript compiler (tsc).
- Include the generated JavaScript files in your project as you would with any other JavaScript files.