基于PureScript函数式博客示例,用TypeScript实现带类型的Box类
Got it, let's add proper TypeScript type definitions to this Box container so you get full type checking for your nextCharForNumberString function. Here's a clean, type-safe implementation:
Step 1: Define the Generic Box Interface
Since Box is a generic container that holds a value of any type, we'll use a generic interface to enforce type consistency across its methods:
interface Box<T> { // map transforms the inner value and returns a new Box with the updated type map: <U>(transform: (value: T) => U) => Box<U>; // fold extracts the inner value and returns the transformed result directly fold: <U>(transform: (value: T) => U) => U; // inspect returns a human-readable string representation inspect: () => string; }
Step 2: Implement the Typed Box Function
Now we'll add type annotations to the Box factory function, so TypeScript can track the type of the value inside the Box at every step:
const Box = <T>(value: T): Box<T> => ({ map: (transform) => Box(transform(value)), fold: (transform) => transform(value), inspect: () => `Box(${value})` });
Step 3: Type-Safe Version of Your Function
With the typed Box in place, your nextCharForNumberString function will get automatic type checking. We'll add a type annotation for the input parameter (and can optionally annotate the return type too):
const nextCharForNumberString = (inputStr: string): string => Box(inputStr) .map(s => s.trim()) // TypeScript infers `s` as string .map(s => Number(s)) // Transforms to number, Box now holds number .map(num => num + 1) // Still number, Box remains Box<number> .map(num => String.fromCharCode(num)) // Transforms to string, Box becomes Box<string> .fold(char => char); // Extracts the final string value
How the Type Checking Works
TypeScript will now catch errors at compile time:
- If you tried to call a number method (like
toFixed) on the trimmed string, it would throw an error immediately - If you passed a non-string value to
nextCharForNumberString, TypeScript would flag it - Every
mapandfoldcall enforces that your transformation function matches the current type of the value inside the Box
内容的提问来源于stack exchange,提问作者Daniel Lidström

