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
| What | Convention |
|---|---|
| variables, functions, methods | camelCase |
| classes, type aliases, interfaces, enums | PascalCase |
| constants & enum members | UPPER_SNAKE or PascalCase |
| private "by convention" | _leadingUnderscore (avoid — use real private) |
| type parameters | T, 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;
Six letters.
Discussion
Loading…