One of the core features of TypeScript is static typing. In JavaScript, variables can hold values of any type at runtime. In TypeScript, you can define the type of a variable explicitly, which helps catch errors at compile - time.
// Defining a variable with a specific type
let age: number = 25;
// This will cause a compile - time error as we are trying to assign a string to a number variable
// age = "twenty - five";
Interfaces in TypeScript are used to define the shape of an object. They allow you to create contracts that other parts of your code must adhere to.
interface Person {
name: string;
age: number;
}
const person: Person = {
name: "John",
age: 30
};
TypeScript supports class - based object - oriented programming. Classes can have properties, methods, and access modifiers like public
, private
, and protected
.
class Animal {
private name: string;
constructor(name: string) {
this.name = name;
}
public makeSound() {
console.log(`${this.name} makes a sound`);
}
}
const cat = new Animal("Cat");
cat.makeSound();
Enums are a way to define a set of named constants. They can be numeric or string - based.
enum Color {
Red,
Green,
Blue
}
let myColor: Color = Color.Green;
console.log(myColor); // Output: 1
Generics allow you to create reusable components that can work with different types.
function identity<T>(arg: T): T {
return arg;
}
let output1 = identity<string>("myString");
let output2 = identity<number>(100);
To start using TypeScript 5, you first need to install it globally using npm:
npm install -g typescript
After writing your TypeScript code in a .ts
file, you can compile it to JavaScript using the tsc
command. For example, if you have a file named app.ts
, you can compile it with:
tsc app.ts
You can use a tsconfig.json
file to configure how TypeScript compiles your code. Here is a basic example:
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
You can gradually introduce TypeScript into existing JavaScript projects. Start by adding a tsconfig.json
file and then start converting your .js
files to .ts
files one by one. You can also use the any
type initially to make the transition smoother.
// JavaScript code converted to TypeScript with any type
let data: any = { message: "Hello" };
console.log(data.message);
Function overloading in TypeScript allows you to define multiple function signatures for a single function.
function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: any, b: any): any {
return a + b;
}
const numResult = add(1, 2);
const strResult = add("Hello", " World");
Union types allow a variable to have one of several types.
function printId(id: number | string) {
console.log(`Your ID is: ${id}`);
}
printId(101);
printId("ABC123");
Type guards are used to narrow down the type within a conditional block.
function printId(id: number | string) {
if (typeof id === "string") {
// Inside this block, TypeScript knows that id is a string
console.log(id.toUpperCase());
} else {
console.log(id);
}
}
Enable strict mode in your tsconfig.json
by setting "strict": true
. This helps catch many common errors early, such as using variables without initializing them or accessing properties that might not exist.
{
"compilerOptions": {
"strict": true
}
}
Interfaces and types should have a single responsibility. This makes the code more modular and easier to understand and maintain. For example, instead of creating a large interface with many unrelated properties, break it down into smaller, focused interfaces.
interface UserInfo {
name: string;
age: number;
}
interface UserContact {
email: string;
phone: string;
}
function displayUser(user: UserInfo & UserContact) {
console.log(`Name: ${user.name}, Age: ${user.age}, Email: ${user.email}`);
}
Adding comments to your TypeScript code is crucial, especially for complex logic or functions. It helps other developers (and your future self) understand the purpose and functionality of the code.
// This function calculates the sum of two numbers
function sum(a: number, b: number): number {
return a + b;
}
TypeScript 5 in the third edition of “Essential TypeScript” offers a powerful set of features that enhance the JavaScript development experience. By understanding the fundamental concepts like static typing, interfaces, classes, enums, and generics, and following the best practices for usage and coding, developers can write more reliable, maintainable, and scalable code. Whether you are working on a small project or a large - scale application, TypeScript 5 can significantly improve the quality of your codebase.