JavaScript & TypeScript Notebook 📜
2‑A What is JavaScript (JS)?
JS is the language of the web, executing in browsers and on servers via Node.js. ECMAScript defines the language spec.
Why TypeScript (TS)?
TypeScript is a typed superset of JS that compiles to JS, adding static typing, interfaces and tooling that catch bugs early. Latest stable TS 5.4 introduces Object.groupBy()
and Map.groupBy()
typings, stricter enum rules and smarter auto‑imports【turn0search2】【turn0search6】.
2‑B Environment Setup
Step | Command |
---|---|
Install Node.js 22 LTS | nvm install 22 && nvm use 22 or installer【turn3search2】 |
Check versions | node -v && npm -v |
Init project | mkdir js‑playground && cd $_ && npm init -y |
Install TypeScript locally | npm i -D typescript |
Generate tsconfig.json | npx tsc --init --rootDir src --outDir dist --strict |
Install ESLint & Prettier | npm i -D eslint prettier eslint-config-prettier eslint-plugin-import |
2‑C Language Basics
// src/index.ts
// 1. Variables
let message: string = 'Hello TS';
// 2. Function
function greet(name: string, shout = false): string {
const line = `Welcome, ${name}`;
return shout ? line.toUpperCase() : line;
}
// 3. Interfaces
interface User { id: number; name: string; }
// 4. Generics
function wrap<T>(value: T): { value: T } { return { value }; }
// 5. Async/Await
async function fetchJson(url: string) {
const res = await fetch(url);
return res.json() as Promise<unknown>;
}
// 6. Modules (ES Modules syntax)
export { greet, User, wrap };
Compile & run:
npx tsc # emits dist/index.js
node dist/index.js
2‑D Testing (JS / TS)
npm i -D jest @types/jest ts-jest
npx ts-jest config:init
npm test
Write test in src/index.test.ts
:
import { greet } from './index';
describe('greet()', () => {
it('returns polite message', () => {
expect(greet('Ada')).toBe('Welcome, Ada');
});
});
Generate coverage:
npm test -- --coverage
2‑E Best Practices
- Prefer
const
/let
overvar
. - Enable
strict
flags intsconfig.json
. - Use ESLint ruleset
eslint:recommended
,plugin:@typescript-eslint/recommended
. - Keep functions small; embrace modules.
- Document with JSDoc or TSDoc comments.
2‑F Challenge
Build a CLI (Command‑Line Interface) that fetches a JSON placeholder API and groups posts by user using new Object.groupBy()
typings from TS 5.4.