TypeScript Fundamentals: Static Typing and Object-Oriented Programming
Core Concepts
TypeScript extends JavaScript by adding static type definitions, enabling compile-time type checking to reduce runtime errors and improve code maintainability.
Installation and Setup
Install the TypeScript compiler globally:
npm install -g typescript
Compile TypeScript files to JavaScript:
tsc filename.ts
Variable Declarations
// Basic type annotations
let text: string = '';
let count: number;
count = 18;
// Type inference when initializing
let items = []; // inferred as any[]
// Union types
let status: 'active' | 'inactive';
let value: number | string;
// Any vs Unknown
let flexible: any; // Can be assigned to other typed variables
let uncertain: unknown; // Type-safe alternative to any
// Type assertions
let numericValue: number;
numericValue = uncertain as number;
numericValue = <number>uncertain;
// Void and Never
function logMessage(): void { console.log('Hello'); }
function throwError(): never { throw new Error('Failed'); }
Object and Functon Types
// Object type with optional properties
interface UserProfile {
username: string;
age?: number;
}
let profile: UserProfile = { username: 'john' };
// Function type signature
let calculator: (x: number, y: number) => number;
calculator = function(a, b) { return a + b; };
Array and Tuple Types
// Array types
let names: string[];
let numbers: Array<number>;
// Tuple - fixed-length array
let coordinates: [number, number];
coordinates = [10, 20];
Advanced Type Features
// Enums
enum UserRole {
Admin = 1,
User = 2
}
// Type aliases
type StatusCode = 200 | 404 | 500;
let responseCode: StatusCode = 200;
// Type assertions
let element = document.getElementById('content')! as HTMLElement;
Compiler Configuration
Create tsconfig.json for project-wide settings:
{
"compilerOptions": {
"target": "ES6",
"module": "CommonJS",
"outDir": "./dist",
"strict": true,
"noImplicitAny": true
},
"include": ["src/**/*"]
}
Object-Oriented Programming
Class Definition
class Person {
// Instance properties
name: string;
private age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
// Method
introduce(): void {
console.log(`I'm ${this.name}, ${this.age} years old`);
}
}
Inheritance and Access Modifiers
class Animal {
protected species: string;
constructor(species: string) {
this.species = species;
}
move(): void {
console.log('Moving...');
}
}
class Dog extends Animal {
constructor() {
super('Canine');
}
bark(): void {
console.log('Woof!');
}
}
Abstract Classes and Interfaces
// Abstract class
abstract class Shape {
abstract calculateArea(): number;
}
// Interface
interface Drawable {
draw(): void;
}
class Circle extends Shape implements Drawable {
constructor(private radius: number) {
super();
}
calculateArea(): number {
return Math.PI * this.radius ** 2;
}
draw(): void {
console.log('Drawing circle');
}
}
Generics
// Generic function
function identity<T>(value: T): T {
return value;
}
// Generic class
class Container<T> {
constructor(private content: T) {}
getValue(): T {
return this.content;
}
}
// Generic constraints
interface Lengthwise {
length: number;
}
function getLength<T extends Lengthwise>(obj: T): number {
return obj.length;
}
Webpack Integration
Package Configuration
{
"scripts": {
"build": "webpack",
"dev": "webpack serve"
},
"devDependencies": {
"webpack": "^5.0.0",
"typescript": "^4.0.0",
"ts-loader": "^9.0.0"
}
}
Webpack Configuration
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.ts', '.js']
}
};
Practical Considerations
- Use
strictcompiler option for comprehensive type checking - Prefer
unknownoveranyfor better type safety - Levearge interfaces for contract-based development
- Utilize generics for reusable, type-safe components
- Implement proper access moidfiers for encapsulation