Lab 09: FP with TypeScript
Step 1: Environment Setup
docker run -it --rm node:20-alpine sh
npm install -g typescript ts-node
mkdir lab09 && cd lab09
npm init -y
npm install fp-ts
echo '{"compilerOptions":{"module":"commonjs","target":"es2020","strict":true,"esModuleInterop":true}}' > tsconfig.jsonStep 2: Option — Safe Nullable Values
// option.ts
import { pipe } from 'fp-ts/function';
import * as O from 'fp-ts/Option';
// Creating Options
const some = O.some(42); // Option<number> with value
const none = O.none; // Option<never> — no value
const fromNull = O.fromNullable(null); // None
const fromValue = O.fromNullable('hello'); // Some('hello')
// Transforming Options
const database: Record<string, { name: string; age: number }> = {
'u1': { name: 'Alice', age: 30 },
'u2': { name: 'Bob', age: 25 },
};
function findUser(id: string): O.Option<{ name: string; age: number }> {
return O.fromNullable(database[id]);
}
function getAge(user: { name: string; age: number }): number {
return user.age;
}
// pipe chains operations left-to-right
const result1 = pipe(
findUser('u1'),
O.map(getAge), // Transform if Some
O.filter(age => age >= 18), // Keep if predicate passes
O.map(age => `Adult, age: ${age}`),
O.getOrElse(() => 'Unknown user'), // Extract with fallback
);
const result2 = pipe(
findUser('u999'), // Not found → None
O.map(getAge),
O.getOrElse(() => 0),
);
console.log(result1); // "Adult, age: 30"
console.log(result2); // 0
// chain (flatMap) — when the transformation itself returns Option
function findEmail(name: string): O.Option<string> {
const emails: Record<string, string> = { Alice: '[email protected]' };
return O.fromNullable(emails[name]);
}
const email = pipe(
findUser('u1'),
O.chain(user => findEmail(user.name)), // Option<string>
O.fold(
() => 'No email found',
email => `Email: ${email}`,
),
);
console.log(email); // "Email: [email protected]"Step 3: Either — Typed Error Handling
Step 4: pipe and flow
Step 5: Either mapLeft and bimap
Step 6: TaskEither for Async Operations
Step 7: Combining Option and Either
Step 8: Capstone — Type-Safe Data Pipeline
Summary
Concept
fp-ts API
Use Case
Last updated
