iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

TS Syntax

TypeScript's syntax is JavaScript's syntax — plus optional type annotations. If you can read JS, you can read 90% of TS instantly.

Anatomy of an annotation

TS
// variable annotation
let name: string = 'Ada';
let age:  number = 36;

// function annotation
function greet(name: string): string {
    return `Hello, ${name}!`;
}

// type alias
type User = { id: number; name: string };

// interface
interface Greetable {
    greet(): string;
}

Semicolons & trailing commas

  • Semicolons are optional but most teams use them. Prettier auto-handles either way.
  • Trailing commas allowed in arrays, objects, parameter lists, type params, tuple types.
  • One statement per line, indent with 2 spaces (community convention).

Comments

TS
// single-line comment
/* block comment */

/**
 * JSDoc — picked up by editors and tools.
 * @param name Who to greet
 * @returns A greeting string
 */
function greet(name: string): string {
    return `Hi, ${name}`;
}

Identifier rules

WhatConvention
variables, functions, methodscamelCase
classes, type aliases, interfaces, enumsPascalCase
constants & enum membersUPPER_SNAKE or PascalCase
private "by convention"_leadingUnderscore (avoid — use real private)
type parametersT, K, V; longer names for clarity
Tip: Run Prettier + ESLint via npm run lint && npm run format. Stop arguing about style; argue about types.

Example

Example
// One declaration per line; semicolons optional but conventional.
let count: number = 0;
const MAX: number = 100;
let active: boolean = true;
Try it Yourself »

Exercise

Annotate a number variable.

let count: = 0;

Test yourself

Q1. Annotate a variable with a type using…
Q2. Semicolons in TS are…
Q3. Most TypeScript codebases indent with…

Discussion

Loading…