TYPESCRIPT
What is TypeScript: Syntax, Usage, and Examples
TypeScript is a strongly typed superset of JavaScript that compiles to plain JavaScript. It adds static types, interfaces, and object-oriented programming features that help catch errors early and improve maintainability. Many modern web applications and large-scale projects use TypeScript to ensure better structure and code reliability.
How to Use TypeScript
Since browsers and Node.js do not run TypeScript directly, you need to compile TypeScript files (.ts
) into JavaScript (.js
) using the TypeScript compiler.
Install TypeScript
You can install TypeScript globally using npm:
npm install -g typescript
Check the installation by running:
tsc --version
This command confirms that TypeScript is installed and ready to use.
Write and Compile TypeScript
Create a hello.ts
file with the following code:
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("Alice"));
To compile it into JavaScript, run:
tsc hello.ts
This command generates a hello.js
file, which you can execute in a browser or Node.js.
What is TypeScript Used For?
TypeScript is useful in many situations, especially when working on large or complex projects. Here are some common use cases:
1. Large JavaScript Applications
TypeScript helps catch type-related errors early, making it easier to maintain large applications. It improves code readability and prevents unexpected runtime issues.
2. Frontend Development
Popular frameworks like Angular are built with TypeScript, and many React projects also use TypeScript for better type safety and developer experience.
3. Backend Development
Many Node.js applications use TypeScript to add structure and prevent common JavaScript errors in backend code. TypeScript makes it easier to manage API endpoints, database interactions, and authentication logic.
Examples of TypeScript in Action
TypeScript extends JavaScript by adding static typing, interfaces, and better support for object-oriented programming.
Declaring Variables with Static Types
TypeScript allows you to specify the type of variables:
let age: number = 25;
let username: string = "Alice";
let isAdmin: boolean = false;
If you try to assign a different type to a variable, TypeScript will throw an error.
Defining Functions with Type Annotations
function add(a: number, b: number): number {
return a + b;
}
console.log(add(5, 10)); // Output: 15
Using Interfaces to Define Object Structures
Interfaces help enforce structure when working with objects:
interface User {
id: number;
name: string;
email?: string; // Optional property
}
const user: User = { id: 1, name: "Alice" };
Creating and Using Classes
TypeScript supports object-oriented programming with classes and constructors.
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
greet(): void {
console.log(`Hello, my name is ${this.name}`);
}
}
const person = new Person("Alice");
person.greet(); // Output: Hello, my name is Alice
TypeScript with Enums
Enums allow you to define a set of named constants:
enum Direction {
Up,
Down,
Left,
Right
}
let move: Direction = Direction.Up;
console.log(move); // Output: 0
What is the Difference Between TypeScript and JavaScript?
1. Type Safety
JavaScript is dynamically typed, meaning a variable can change types at any time. TypeScript enforces static types, reducing runtime errors.
// JavaScript allows any type
let value = 42;
value = "Hello"; // No error
// TypeScript prevents this
let value: number = 42;
value = "Hello"; // Type error
2. Compilation
JavaScript runs directly in browsers, while TypeScript requires compilation. This extra step allows for better error detection before running the code.
3. Interfaces and Generics
TypeScript introduces interfaces and generics, which JavaScript lacks.
function identity<T>(value: T): T {
return value;
}
console.log(identity<string>("Hello")); // Output: Hello
console.log(identity<number>(42)); // Output: 42
Learn More About TypeScript
TypeScript Configuration
A tsconfig.json
file lets you configure TypeScript options for your project.
{
"compilerOptions": {
"target": "ES6",
"strict": true}
}
TypeScript with React
React supports TypeScript using .tsx
files.
interface Props {
name: string;
}
const Greeting: React.FC<Props> = ({ name }) => <h1>Hello, {name}!</h1>;
TypeScript in Node.js
TypeScript works well in Node.js applications.
import express from "express";
const app = express();
app.get("/", (req, res) => res.send("Hello TypeScript!"));
app.listen(3000, () => console.log("Server running on port 3000"));
Common TypeScript Features
1. Type Assertions
TypeScript allows you to tell the compiler that you know the type of a variable when TypeScript cannot infer it correctly.
let someValue: unknown = "Hello TypeScript";
let strLength: number = (someValue as string).length;
2. Non-Nullable Types
By default, TypeScript prevents null
or undefined
values unless explicitly allowed.
function greet(name: string): void {
console.log(`Hello, ${name}`);
}
// TypeScript will throw an error if you try to pass null
greet("Alice"); // Works
greet(null); // Error
3. Readonly Properties
You can create properties that cannot be changed after initialization.
interface Car {
readonly brand: string;
}
const myCar: Car = { brand: "Toyota" };
myCar.brand = "Honda"; // Error: Cannot assign to 'brand' because it is a read-only property.
4. Optional Chaining
Optional chaining makes it easier to access deeply nested properties without checking for null
or undefined
.
let user = { profile: { name: "Alice" } };
console.log(user.profile?.name); // Output: Alice
console.log(user.profile?.age); // Output: undefined
5. Nullish Coalescing
This operator (??
) provides a fallback value for null
or undefined
.
let input: string | null = null;
let name = input ?? "Guest";
console.log(name); // Output: Guest
6. Tuple Types
Tuples allow you to define an array with a fixed number of elements and specific types.
let user: [string, number] = ["Alice", 25];
TypeScript enhances JavaScript by adding static types, interfaces, and object-oriented programming features. It helps you catch errors early, write maintainable code, and build scalable applications.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.