Kembali ke BlogProgramming Languages
Getting Started with TypeScript: A Beginner's Guide
10 mnt baca
typescriptjavascriptbeginnerstutorial

Getting Started with TypeScript: A Beginner's Guide
Why TypeScript?
TypeScript has rapidly become one of the most loved programming languages. But why?
- Static typing catches errors early
- Better IDE support with autocompletion
- Improved code maintainability
- Great tooling for large applications
Installation
First, install TypeScript globally:
npm install -g typescript
Check the installation:
tsc --version
Your First TypeScript Program
Create a file called hello.ts:
// Basic types let message: string = "Hello, TypeScript!"; let count: number = 42; let isActive: boolean = true; let numbers: number[] = [1, 2, 3, 4, 5]; // Functions with type annotations function greet(name: string): string { return `Hello, ${name}!`; } // Interfaces interface User { id: number; name: string; email: string; age?: number; // Optional property } // Using the interface const user: User = { id: 1, name: "John Doe", email: "john@example.com" }; console.log(greet(user.name));
Key TypeScript Features
1. Type Inference
TypeScript is smart enough to infer types:
let name = "Alice"; // TypeScript infers 'string' let age = 30; // TypeScript infers 'number' // No need to explicitly type everything!
2. Union Types
Variables can hold multiple types:
let id: string | number; id = "ABC123"; // Valid id = 456; // Also valid // id = true; // Error: boolean not allowed
3. Generics
Create reusable components:
function identity<T>(value: T): T { return value; } let stringResult = identity<string>("hello"); let numberResult = identity<number>(42); // TypeScript can infer the generic type let inferredResult = identity("auto-detected");
4. Advanced Types
// Pick - Select specific properties type UserPreview = Pick<User, 'id' | 'name'>; // Omit - Exclude properties type UserWithoutEmail = Omit<User, 'email'>; // Partial - Make all properties optional type PartialUser = Partial<User>; // Readonly - Prevent modifications type ReadonlyUser = Readonly<User>;
Compiling TypeScript
Compile your TypeScript file:
tsc hello.ts
This generates hello.js that can run in any JavaScript environment.
Configuration with tsconfig.json
Create a tsconfig.json file:
{ "compilerOptions": { "target": "ES2020", "module": "commonjs", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "outDir": "./dist", "rootDir": "./src" }, "include": ["src/**/*"], "exclude": ["node_modules"] }
Best Practices
- Use explicit types for function parameters and returns
- Avoid using
any- it defeats the purpose of TypeScript - Leverage union types instead of optional parameters
- Use interfaces for object shapes
- Enable strict mode in tsconfig.json
Common Mistakes to Avoid
// ❌ Bad - using 'any' function processData(data: any) { return data.toUpperCase(); } // ✅ Good - proper typing function processData(data: string): string { return data.toUpperCase(); } // ❌ Bad - ignoring null checks function getLength(str: string) { return str.length; // What if str is null? } // ✅ Good - handling null function getLength(str: string | null): number { return str?.length ?? 0; }
Next Steps
- Learn about advanced types (Mapped, Conditional)
- Explore decorators for metadata
- Try TypeScript with React/Vue/Angular
- Set up a build pipeline with Webpack or Vite
TypeScript is a powerful tool that will make you a better JavaScript developer. Happy coding!
