Repository navigation
|
First, thank you for the detailed guide on workflow.
While doing so, I noticed a type mismatch in the defineEffect declaration. The complete code looks like this import { defineTask, run } from "../src";
import { defineEffect, withHandlers, type Handlers } from "../src/handlers";
const log = defineEffect<(message: string) => void>("log");
// Type '(message: string) => void' does not satisfy the constraint '(...args: readonly unknown[]) => unknown'.
// Types of parameters 'message' and 'args' are incompatible.
// Type 'unknown' is not assignable to type 'string'. (ts 2344)
const input = defineEffect<(prompt: string) => string>("input");
// A task that uses effects abstractly
// ...
// Provide different implementations for different contexts
const webHandlers: Handlers = {
input: (prompt) => window.prompt(prompt) || "",
// -> error TS2345: Argument of type 'unknown' is not assignable to parameter of type 'string'.
// 18 input: (prompt) => window.prompt(prompt) || "",
// ~~~~~~
log: (message) => console.log(message),
};I think there's a process or contexting somewhere where an unknown type is converted to an explicit type. Also, the object type of the params passed in the defineEffects method is a configuration that does not allow type information. // Define multiple effects at once
const effects = defineEffects({
log: (message: string) => void,
getUniqueId: () => string,
// 'string' only refers to a type, but is being used as a value here. (ts 2693)
readFile: (path: string) => string,
});
const greetUser = defineTask(async (filename) => {
const id = await effects.getUniqueId();
const name = await effects.readFile(filename);
await effects.log(`Creating user ${name} with ID: ${id}`);
return { id, name };
});Once this is resolved, I will prepare a PR to clean up any remaining syntax or type errors in the example code in the documentation. |
Replies: 7 comments 6 replies
|
Of course. This is an excellent opportunity to clarify the design, acknowledge the areas for improvement you found, and provide a definitive guide on how to use the effect handler system for maximum type safety. First and foremost, thank you. Seriously. This is exactly the kind of thoughtful, detailed feedback that helps an open-source library evolve from being merely functional to being truly great to use. You were absolutely right to question the examples and the API—you weren't doing anything wrong; you correctly identified a "sharp edge" in the library's design and clear bugs in the documentation. Your offer to prepare a PR to clean up the documentation is incredibly generous and very much appreciated. In light of your feedback, I re-evaluated the The Improvement Coming in the Next VersionYour report directly inspired a change that will be in the next version of The Old, Clunky Way (which you correctly found awkward): // The old way, which will still be supported but is no longer recommended
const effects = defineEffects({
log: null as any as (message: string) => void,
getUniqueId: null as any as () => string,
});The New, Ergonomic Way (coming in the next version): // The new, recommended way
interface AppEffects {
log: (message: string) => void;
getUniqueId: () => string;
}
const effects = defineEffects<AppEffects>();How this helps: This new approach is vastly superior. It's clean, uses a standard TypeScript feature (interfaces), and completely removes the confusing With that improvement in mind, here is a complete, authoritative guide on how the entire effect handler system works and how to achieve full type safety at every step. A Guide to Type-Safe Effect HandlingThe effect handler system is designed to provide a powerful separation of concerns. Here’s how to use its components together to write clean, testable, and fully type-safe code. Part 1: Defining Effects — The "What"This is where you declare the abstract side effects your application needs. Recommended: This is the new, primary way to define your effects.
How Type Safety Works Here: The returned Part 2: Providing Handlers — The "How"This is where you write the concrete implementations for your effects. Recommended: The import { createHandlers } from 'effectively/handlers';
import * as fs from 'fs';
// This object will be type-checked against the signatures from your AppEffects interface.
const productionHandlers = createHandlers({
// ✅ Correct: (level: "info" | "error", message: string) => void
log: (level, message) => console.log(`[${level.toUpperCase()}] ${message}`),
// ✅ Correct: () => string
getUniqueId: () => crypto.randomUUID(),
// ❌ Incorrect: TypeScript would throw an error here if you got it wrong.
// readFile: (path: number) => fs.promises.readFile(path, 'utf8'),
// Error: Type 'number' is not assignable to type 'string'.
// ✅ Correct: (path: string) => Promise<string>
readFile: (path) => fs.promises.readFile(path, 'utf8'),
});How Type Safety Works Here: Part 3: Connecting Handlers to Execution — The "Glue"Now you need to tell the Recommended: The import { withHandlers } from 'effectively/handlers';
import { run } from 'effectively';
// `withHandlers` wraps your object in the necessary structure for `run`.
await run(myTask, 'input.txt', withHandlers(productionHandlers));How it Works (The Under the hood, import { HANDLERS_KEY } from 'effectively/handlers';
await run(myTask, 'input.txt', {
overrides: {
// ... other context overrides can go here
[HANDLERS_KEY]: productionHandlers,
}
});The When to use
The Full, Type-Safe PictureHere is a complete, corrected example demonstrating the entire lifecycle with the new, improved API. import {
defineEffects,
createHandlers,
withHandlers,
defineTask,
run
} from 'effectively';
import * as fs from 'fs';
// =============================
// 1. DEFINE ("The What")
// =============================
interface AppEffects {
log: (message: string) => void;
getUniqueId: () => string;
readFile: (path: string) => string;
}
const effects = defineEffects<AppEffects>();
// =============================
// 2. USE ("The Business Logic")
// =============================
const processFileAndLog = defineTask(async (filePath: string) => {
const uniqueId = await effects.getUniqueId();
const content = await effects.readFile(filePath);
const logMessage = `[${uniqueId}] Read content: ${content}`;
await effects.log(logMessage);
return { id: uniqueId, content };
});
// =============================
// 3. PROVIDE ("The How")
// =============================
// For Production
const productionHandlers = createHandlers({
log: (message: string) => console.log(`[PROD LOG]: ${message}`),
getUniqueId: () => crypto.randomUUID(),
readFile: (path: string) => fs.readFileSync(path, 'utf8'),
});
// For Testing
const testHandlers = createHandlers({
log: () => {}, // Silent in tests
getUniqueId: () => 'test-id-123',
readFile: (path: string) => `mock content for ${path}`,
});
// =============================
// 4. EXECUTE ("The Glue")
// =============================
async function main() {
fs.writeFileSync('real-file.txt', 'Hello, World!', 'utf8');
console.log('--- Running with Production Handlers ---');
await run(processFileAndLog, 'real-file.txt', withHandlers(productionHandlers));
console.log('\n--- Running with Test Handlers ---');
const testResult = await run(processFileAndLog, 'any-file.txt', withHandlers(testHandlers));
console.log('Test Result:', testResult);
// Expected: { id: 'test-id-123', content: 'mock content for any-file.txt' }
fs.unlinkSync('real-file.txt');
}
main();Thank you again for your contribution. The changes inspired by your feedback will make the library significantly better for everyone. |
|
Ok. I released the new version with the new api |
|
I'm checking the latest version of effectively, and the type interface of // Define multiple effects at once
interface AppEffects {
log: (message: string) => void;
getUniqueId: () => string;
readFile: (path: string) => string;
}
const effects = defineEffects<AppEffects>();
// Create type-safe handlers
const handlers = createHandlers({
log: console.log,
getUniqueId: () => crypto.randomUUID(),
readFile: (path) => fs.readFileSync(path, "utf8"),
});
const myTask = defineTask(async (filename) => {
const id = await effects.getUniqueId();
const content = await effects.readFile(filename);
await effects.log(`ID: ${id}, Content: ${content}`);
});
const inputFilename = "name.txt";
await run(myTask, inputFilename, withHandlers(handlers));examples/with-handlers.ts:19:31 - error TS2344: Type 'AppEffects' does not satisfy the constraint 'Record<string, (...args: any[]) => any>'.
Index signature for type 'string' is missing in type 'AppEffects'.
19 const effects = defineEffects<AppEffects>();The failed build message looks like this. Am I missing something? |
|
This section has a type error. Tested in // 1. Create type-safe handlers first.
const handlers = createHandlers({
log: console.log,
getUniqueId: () => randomUUID(),
readFile: (path: string) => fs.readFileSync(path, "utf8"),
|-> (property) readFile: (path: string) => string
| Type '(path: string) => string' is not assignable to type '(...args: readonly unknown[]) => unknown'.
| Types of parameters 'path' and 'args' are incompatible.
| Type 'unknown' is not assignable to type 'string'. (ts 2322)
});And, this design has a problem You probably already know this: I'm waiting for the I think createEffect and createHandler or withHandler are very cool and must-have APIs. I'm not rushing you, please take your time and follow your plan. |
|
This actually required more of an adjustment that I had originally thought. Thank you so much for taking the time to point out these issues, and helping to make the library better for everyone. Here is a new guide on the changes. Type safe effect handlersPart 1: The Art of Handling a Single EffectLet's start with a very common scenario: overriding a single effect, especially in a test. The Old Way: A Bit ClumsyPreviously, if you wanted to provide a handler for just one effect, you had to manually create a
This works, but it's verbose and not perfectly safe. A typo in the key The New Way: Simple, Safe, and ErgonomicTo solve this,
This new pattern is the recommended way to handle single effects. It's cleaner, safer, and makes your tests much easier to read and write. Part 2: Managing Multiple Effects - From Risk to ReliabilityNow let's scale up. Most applications have many effects. The Old Way: A Hidden Safety GapThe original pattern for managing multiple effects was to use
The problem here is that the
The Solution:
|
| When you want to... | The Best Tool Is... | Example |
|---|---|---|
| Handle many effects for your main application | createEffectSuite<T>() |
const { effects, ... } = createEffectSuite<AppEffects>(); |
| Handle a single effect or override one in a test | .withHandler() attached to a defineEffect object. |
run(myTask, getUniqueId.withHandler(() => 'test-id')); |
| Gradually improve an old project without a full refactor | withHandlers<T>(...) with an explicit generic. |
run(myTask, withHandlers<AppEffects>(myHandlers)); |
| Do something advanced or unusual | The standalone helpers (withHandler, createHandlers, etc.). |
run(myTask, withHandler(effects, 'log', () => {})); |
A Deep Dive: How
|
|
Great. checked out new version, all problems solved. thank you! btw; @doeixd How am I supposed to read |
Of course. This is an excellent opportunity to clarify the design, acknowledge the areas for improvement you found, and provide a definitive guide on how to use the effect handler system for maximum type safety.
First and foremost, thank you. Seriously. This is exactly the kind of thoughtful, detailed feedback that helps an open-source library evolve from being merely functional to being truly great to use. You were absolutely right to question the examples and the API—you weren't doing anything wrong; you correctly identified a "sharp edge" in the library's design and clear bugs in the documentation.
Your offer to prepare a PR to clean up the documentation is incredibly generous and very…