TypeScript 101: A Beginner's Guide
TypeScript is a strongly typed superset of JavaScript that compiles down to plain JavaScript. It offers additional features like static typing, interfaces, enums, and more, making code safer and easier to maintain.
Why TypeScript?
- Static Typing: Catches type-related errors during development.
- Enhanced IDE Support: Provides better autocompletion, code navigation, and debugging tools.
- Better Documentation: Type annotations make your code more self-explanatory.
- Interoperability: Works with existing JavaScript code.
- Maintainability: Makes it easier to scale projects and collaborate in teams.
Basic TypeScript Concepts
1. Installing TypeScript
You need Node.js installed first.
npm install -g typescript
You can check the version using:
tsc --version
2. Compiling TypeScript
Create a .ts
file (e.g., example.ts
) and write your code. Then compile it to JavaScript:
tsc example.ts
This generates a .js
file that can run in any environment supporting JavaScript.
Key Features of TypeScript
1. Type Annotations
TypeScript allows you to specify types for variables, function parameters, and return values.
let age: number = 25;
let name: string = "John";
let isStudent: boolean = true;
function add(a: number, b: number): number {
return a + b;
}
- Common Types:
number
string
boolean
any
(disables type-checking)void
(for functions that return nothing)undefined
/null
- Arrays:
number[]
orArray<number>
- Tuples:
[string, number]
- Objects:
{ key: valueType }
2. Interfaces
Interfaces define the shape of an object, enforcing a structure.
interface Person {
name: string;
age: number;
isStudent?: boolean; // Optional property
}
const john: Person = {
name: "John",
age: 25,
};
3. Classes and Access Modifiers
TypeScript supports OOP with class
, interface
, and modifiers like private
, public
, and protected
.
class Animal {
private name: string;
constructor(name: string) {
this.name = name;
}
public getName(): string {
return this.name;
}
}
const dog = new Animal("Buddy");
console.log(dog.getName());
4. Enums
Enums allow you to define a set of named constants.
enum Color {
Red,
Green,
Blue,
}
let favoriteColor: Color = Color.Green;
console.log(favoriteColor); // Output: 1 (index of Green)
5. Generics
Generics enable you to create reusable components that work with any data type.
function identity<T>(value: T): T {
return value;
}
const number = identity<number>(42);
const string = identity<string>("Hello");
6. Union and Intersection Types
- Union Types: A variable can hold one of several types.
let id: string | number;
id = "123";
id = 123;
- Intersection Types: Combine multiple types into one.
interface A { a: string; }
interface B { b: number; }
type C = A & B;
const obj: C = { a: "Hello", b: 42 };
7. Type Aliases
Type aliases create custom types.
type ID = string | number;
function printID(id: ID): void {
console.log(id);
}
Advanced Features
1. Type Assertions
Used when you know more about a variable's type than TypeScript does.
let value: any = "Hello, World!";
let strLength: number = (value as string).length;
2. Modules
TypeScript supports ES6 modules for code organization.
// math.ts
export function add(a: number, b: number): number {
return a + b;
}
// main.ts
import { add } from "./math";
console.log(add(5, 3));
Compile with:
tsc --module system main.ts
TypeScript Configuration
To configure your project, create a tsconfig.json
file in your project root:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
Now you can compile your project with:
tsc
Best Practices
- Always use
strict
mode for better type checking. - Use interfaces to define object shapes.
- Avoid using
any
unless absolutely necessary. - Use type aliases and generics for reusable code.
- Break your code into modules for better organization.
Learning Resources
- Official Docs: TypeScript Documentation
- Play with TypeScript: TypeScript Playground
- Tutorials:
- TypeScript Handbook
- FreeCodeCamp & Codecademy TypeScript courses
Example Project
Here’s a simple example to tie it all together:
File: index.ts
interface Product {
id: number;
name: string;
price: number;
}
const products: Product[] = [
{ id: 1, name: "Laptop", price: 1000 },
{ id: 2, name: "Mouse", price: 20 },
];
function getProductById(id: number): Product | undefined {
return products.find(product => product.id === id);
}
console.log(getProductById(1));
Compile and run:
tsc index.ts
node index.js
TypeScript bridges the gap between developer productivity and JavaScript’s flexibility, enabling you to write cleaner, safer, and more scalable code! 🎉