TypeScript Fundamentals
• From Basics to Advanced
Arvind Prajapati
Introduction to TypeScript
• • Superset of JavaScript
• Adds static typing
• Improves maintainability
Setting Up TypeScript
• • Install: npm install -g typescript
• tsconfig.json for configuration
npm install -g typescript
npx tsc --init
Basic Types
• • number, string, boolean
• array, tuple, enum
• any, unknown, void, never let isDone: boolean = false;
let age: number = 30;
let name: string = 'Arvind';
Type Inference
• • TS infers type when possible
• Annotations for clarity
let counter = 10; // inferred as number
Functions
• • Parameter & return types
• Optional/default parameters
function greet(name: string = 'User'): string
{
return `Hello, ${name}`;
}
Interfaces
• • Shape of an object
• Optional & readonly properties
interface Person {
name: string;
age?: number;
}
Classes
• • Supports OOP concepts
• Access modifiers
• Inheritance class Animal {
constructor(public name: string) {}
move() { console.log('Moving'); }
}
Generics
• • Flexible reusable components
• Constraints possible
function identity<T>(value: T): T {
return value;
}
Advanced Types
• • Union & Intersection
• Type Guards
• Utility Types type ID = string | number;
function printId(id: ID) {
if (typeof id === 'string')
console.log(id.toUpperCase());
}
Modules
• • Organize code with import/export
// math.ts
export function add(a: number, b: number)
{ return a + b; }
Decorators
• • Experimental feature
• Add metadata to classes/methods
function sealed(constructor: Function) {
Object.seal(constructor);
}
TypeScript with React
• • TSX files
• Props & State typing
type Props = { name: string };
const Hello: React.FC<Props> = ({ name }) =>
<h1>Hello {name}</h1>;
Best Practices
• • Use strict mode
• Avoid any
• Keep types DRY
Q&A
• Questions?