About the TypeScript online compiler
TypeScript is JavaScript with a type layer on top. This online TypeScript compiler type-checks your snippet and then runs it, so you see both compile-time errors and runtime output in one place — the fastest way to learn how interfaces, generics and unions behave in practice.
Start with typing function parameters and return values, then move on to interfaces versus type aliases, union and literal types, optional properties, and generics. Every mistake you make here shows up as a red error before the program even runs, which is exactly the habit TypeScript is meant to build.
- →Learning generics by writing a typed identity or wrapper function
- →Modelling API responses with interfaces before writing the fetch
- →Testing whether a union narrows correctly inside an if block
- →Practising utility types like Partial, Pick and Record
TypeScript sample programs you can run right now
Copy any snippet into the editor above and press Run. Each one is short on purpose — retype it from memory afterwards.
Interfaces and narrowing
interface User { name: string; age: number; admin?: boolean }
function describe(u: User): string {
return u.admin ? `${u.name} (admin)` : `${u.name}, ${u.age}`;
}
console.log(describe({ name: "Aarav", age: 21 }));
console.log(describe({ name: "Priya", age: 24, admin: true }));
The ? marks admin as optional, so the first call compiles even without it.
A generic function
function first<T>(items: T[]): T | undefined {
return items[0];
}
console.log(first([10, 20, 30]));
console.log(first(["a", "b"]));
T is inferred from the argument, so first([10,20]) returns number | undefined without any annotation at the call site.
Common TypeScript errors and how to fix them
Type 'string' is not assignable to type 'number'
Why: The value's type does not match the declared type.
Fix: Either change the annotation or convert the value with Number(x) / String(x).
Property 'x' does not exist on type '{}'
Why: TypeScript inferred an empty object type.
Fix: Declare an interface or annotate the variable so the property is known.
Object is possibly 'undefined'
Why: Strict null checks caught an access that could fail at runtime.
Fix: Use optional chaining (a?.b) or an explicit if (a) guard.
TypeScript syntax cheatsheet
| Concept | Syntax |
|---|
| Typed variable | let count: number = 0; |
| Interface | interface Point { x: number; y: number } |
| Union type | type Status = 'on' | 'off'; |
| Generic | function id<T>(v: T): T { return v } |
| Optional property | interface A { b?: string } |
| Type assertion | const el = v as string; |
TypeScript compiler FAQs
Is the TypeScript compiler here the real tsc?
Your code is compiled to JavaScript and executed, so syntax and type errors surface exactly as they would in a local project.
Can I import npm packages?
No — snippets run standalone with no package installation, so keep examples dependency free.
Keep going after the compiler
Running snippets builds speed; the 17-chapter course builds understanding. Work through the TypeScript chapters, take the quiz, then claim your certificate.
Other compilers: JavaScript compiler, Python 3 compiler, Java compiler, C compiler, C++ compiler, Go compiler, Rust compiler, HTML compiler, CSS compiler, SQLite compiler
TypeScript tutorial: five steps from blank editor to working program
This walkthrough takes you from plain JavaScript to typed TypeScript: annotating values, describing object shapes, narrowing unions and writing your first generic. Every step compiles in the editor above.
1. Annotate what a function takes and returns
Types on parameters and return values are the highest-value annotations you can write — they document the function and catch wrong call sites immediately.
function area(width: number, height: number): number {
return width * height;
}
console.log(area(3, 4));
2. Describe object shapes with interfaces
An interface names a shape so you can reuse it. Optional fields get a ?, and readonly fields cannot be reassigned after creation.
interface Student {
name: string;
marks: number;
email?: string;
}
const s: Student = { name: "Diya", marks: 91 };
console.log(s);
3. Use unions instead of loose strings
A union of literal types restricts a value to a known set, so a typo becomes a compile error rather than a runtime surprise.
type Status = "draft" | "published" | "archived";
function label(s: Status) {
return s.toUpperCase();
}
console.log(label("draft"));
4. Narrow a union before using it
TypeScript follows your if-checks. After a typeof or in check, the type inside that branch is narrowed automatically — no casting needed.
function show(v: string | number) {
if (typeof v === "string") return v.trim();
return v.toFixed(2);
}
console.log(show(3.14159), show(" hi "));
5. Write one generic function
A generic keeps the caller's type instead of collapsing it to any. Here the return type is exactly whatever was passed in.
function first<T>(items: T[]): T | undefined {
return items[0];
}
console.log(first([10, 20]));
console.log(first(["a", "b"]));
Practice exercises with solutions
Try each one in the editor above before opening the solution — the struggle is where the learning happens.
Beginner
Type a function that takes a list of numbers and returns their average.
Hint: The parameter is number[] and the return is number.
Show solution
function average(nums: number[]): number {
return nums.reduce((a, b) => a + b, 0) / nums.length;
}
console.log(average([2, 4, 6]));
Intermediate
Model a shape that is either a circle or a rectangle, and compute its area with one function.
Hint: Use a discriminated union with a common 'kind' field.
Show solution
type Shape =
| { kind: "circle"; r: number }
| { kind: "rect"; w: number; h: number };
function area(s: Shape): number {
return s.kind === "circle" ? Math.PI * s.r ** 2 : s.w * s.h;
}
console.log(area({ kind: "rect", w: 2, h: 3 }));
Advanced
Write a type-safe pick helper that returns a subset of an object's keys.
Hint: Constrain the key type with K extends keyof T and return Pick<T, K>.
Show solution
function pick<T extends object, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
const out = {} as Pick<T, K>;
keys.forEach((k) => (out[k] = obj[k]));
return out;
}
console.log(pick({ a: 1, b: 2, c: 3 }, ["a", "c"]));
Why learn TypeScript?
TypeScript catches type mistakes before the program runs, which matters most in codebases too large to hold in your head.
Editors use its type information for accurate autocomplete and refactoring, so you spend less time reading source to learn an API.
What TypeScript is used for
- →Large front-end applications and design systems
- →Node.js backends and shared client/server types
- →Publishing typed npm libraries
- →Migrating existing JavaScript projects incrementally
Ready for structured practice? The 17-chapter TypeScript course takes these ideas one at a time, with a quiz and a certificate at the end.