JavaScript with a type system bolted on โ catches whole categories of bugs before your code ever runs, and is the default choice for most modern large-scale web frontends and backends. Copy-paste examples plus live Run/Submit exercises.
let message: string = "Hello, world!";
console.log(message);
let age: number = 25;
let name: string = "Sam";
let isAdult: boolean = true;
let scores: number[] = [90, 85, 77];
let id: string | number = 42; // union type โ id can be EITHER
TypeScript's core feature โ describing the exact shape an object must have.
interface Dog {
name: string;
age: number;
}
function describe(d: Dog): string {
return `${d.name} is ${d.age} years old`;
}
function add(a: number, b: number): number {
return a + b;
}
const multiply = (a: number, b: number): number => a * b;
Write one function that works safely with any type, without giving up type-checking.
function firstItem<T>(arr: T[]): T {
return arr[0];
}
const n = firstItem<number>([1, 2, 3]); // n is typed as number
class Dog {
constructor(public name: string, public age: number) {}
bark(): void {
console.log(`${this.name} says woof!`);
}
}
// const d = new Dog("Rex", 3); d.bark();
Full runnable programs, type-checked and run in a real TypeScript sandbox โ same workspace as the other cheat sheets.
const nums: number[] = [4, 8, 15, 16, 23, 42];
const sum = nums.reduce((a, b) => a + b, 0);
console.log(sum);
function reverseStr(s: string): string {
return s.split("").reverse().join("");
}
console.log(reverseStr("typescript"));
interface Person {
name: string;
age: number;
}
const people: Person[] = [
{ name: "Sam", age: 25 },
{ name: "Ana", age: 17 },
{ name: "Lee", age: 31 },
];
const adults = people.filter(p => p.age >= 18);
adults.forEach(p => console.log(p.name));
const text = "the cat sat on the mat the cat ran";
const counts = new Map<string, number>();
for (const word of text.split(" ")) {
counts.set(word, (counts.get(word) || 0) + 1);
}
for (const [word, n] of counts) {
console.log(`${word}: ${n}`);
}