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 late

TypeScript Saves the Day#

// TypeScript catches it before you even run
function greet(name: string): string {
return "Hello, " + name.toUpperCase();
}
greet(123); // Nope! Compile error
greet("LUKKID"); // All good!

Basic Types That’ll Save Your Life#

// The basics
let name: string = "LUKKID";
let age: number = 20;
let isAwesome: boolean = true;
// Arrays
let skills: string[] = ["React", "Node.js", "Python"];
let numbers: Array<number> = [1, 2, 3];
// Objects with interfaces
interface 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 number
const firstName = getFirst(["a", "b"]); // knows it's string

3. Union Types#

type Status = "pending" | "approved" | "rejected";
function updateStatus(id: string, status: Status) {
// Only these 3 values allowed!
}
updateStatus("1", "approved"); // Works
updateStatus("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#

  1. Start with any — then slowly add real types
  2. Turn on strict mode — hurts at first, worth it later
  3. Use VSCode — the autocomplete is insane
  4. 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/
Author
LUKKID
Published at
2024-03-15
License
CC BY-NC-SA 4.0