344 words
2 minutes
TypeScript Changed Everything
TypeScript Changed Everything
Switching from plain JavaScript to TypeScript was one of the best decisions I ever made.
The JavaScript Problem
// JavaScript be like...function greet(name) { return "Hello, " + name.toUpperCase();}
greet(123); // Runtime Error!// You only find out when it's too lateTypeScript Saves the Day
// TypeScript catches it before you even runfunction greet(name: string): string { return "Hello, " + name.toUpperCase();}
greet(123); // Nope! Compile errorgreet("LUKKID"); // All good!Basic Types That’ll Save Your Life
// The basicslet name: string = "LUKKID";let age: number = 20;let isAwesome: boolean = true;
// Arrayslet skills: string[] = ["React", "Node.js", "Python"];let numbers: Array<number> = [1, 2, 3];
// Objects with interfacesinterface User { id: number; name: string; email?: string; // Optional stuff}
const user: User = { id: 1, name: "LUKKID"};My Favorite Features
1. Interfaces
interface Project { id: string; title: string; tech: string[]; completed: boolean;}
function displayProject(project: Project) { console.log(`${project.title} - ${project.tech.join(", ")}`);}2. Generics
function getFirst<T>(arr: T[]): T | undefined { return arr[0];}
const firstNumber = getFirst([1, 2, 3]); // knows it's numberconst firstName = getFirst(["a", "b"]); // knows it's string3. Union Types
type Status = "pending" | "approved" | "rejected";
function updateStatus(id: string, status: Status) { // Only these 3 values allowed!}
updateStatus("1", "approved"); // WorksupdateStatus("1", "maybe"); // Nope!React + TypeScript = Perfect Combo
interface ButtonProps { label: string; onClick: () => void; variant?: "primary" | "secondary";}
const Button: React.FC<ButtonProps> = ({ label, onClick, variant = "primary"}) => { return ( <button className={`btn btn-${variant}`} onClick={onClick} > {label} </button> );};
// VSCode autocomplete goes crazy here<Button label="Click me" onClick={() => alert("Hi!")} />Tips for Making the Switch
- Start with
any— then slowly add real types - Turn on strict mode — hurts at first, worth it later
- Use VSCode — the autocomplete is insane
- Read the errors — TypeScript tells you exactly what’s wrong
My tsconfig.json
{ "compilerOptions": { "target": "ES2020", "module": "ESNext", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }}TypeScript = JavaScript that grew up
Trust me, once you go TS, you never go back!
TypeScript Changed Everything
https://blog.lukkid.dev/posts/typescript-guide/