TypeScript chapters

Chapter 16 of 17

TypeScript Syntax Cheatsheet

Try this in our TypeScript Compiler →

Everything in one place

Use this chapter as a quick reference once you've worked through the rest of the course. It collects every core construct of TypeScript into runnable, copy-pasteable snippets you can scan whenever you forget the exact syntax.

Hello world & variables

const greet = (name: string): string => `Hello, ${name}!`;
console.log(greet("World"));

let age: number = 25;
const name: string = "Aman";
let isStudent: boolean = true;

Data types & operators

let n: number = 42;
let s: string = "hello";
let b: boolean = true;
let arr: number[] = [1, 2, 3];
let maybe: string | null = null;

const a = 10, b = 3;
console.log(a + b, a % b);
console.log(a > b && b < 5);

Conditionals & loops

const score: number = 72;
if (score >= 90) console.log("A");
else if (score >= 60) console.log("Pass");
else console.log("Fail");

for (let i = 0; i < 5; i++) console.log(i);

const items: string[] = ["a", "b"];
for (const x of items) console.log(x);

Functions & arrays

function add(a: number, b: number): number {
  return a + b;
}
const square = (x: number) => x * x;

const nums: number[] = [10, 20, 30];
const doubled = nums.map((n) => n * 2);
const sum = nums.reduce((t, n) => t + n, 0);

Strings & objects

const name = "PlayLearn";
console.log(name.length);
console.log(name.toUpperCase());
const greet = `Hello, ${name}!`;

interface User {
  name: string;
  age: number;
}
const u: User = { name: "Aman", age: 20 };
console.log(u.name);

Errors, modules & I/O

try {
  JSON.parse("not json");
} catch (err: unknown) {
  if (err instanceof Error) console.error(err.message);
}

// math.ts
export function add(a: number, b: number): number { return a + b; }

// main.ts
import { add } from "./math";
console.log(add(2, 3));

import fs from "node:fs/promises";
const text: string = await fs.readFile("notes.txt", "utf8");
console.log(text);

How to use this page

Bookmark it. When you start a new project, open this cheatsheet alongside your editor and use it as a syntax lookup. Once a construct becomes second nature you'll stop needing the reference for it — and that's exactly when you know you've mastered that part of TypeScript.

Practice and verify

Run reference snippets separately; they are not a single source file to concatenate. Check required imports and entry points for each.

Try it yourself

Output
Run your project to see output here.
Ctrl/Cmd+Enter runs · Ctrl/Cmd+S downloads the project · Local auto-save is always on