#Typing the result of a chain of function calls

4 messages · Page 1 of 1 (latest)

fringe oar
#

Hello, I'm trying to recreate a middleware implementation similar to middy.js (more for my own understanding than anything), but I'm struggling with how to correctly type the middleware factory.

Here's a Playground link for the implementation of the factory and a desired outcome.

I think for the end handler to receive a correctly typed event, I need to supply a return type to/for the use calls and use that to modify types within the factory/handler. The problem here is that I have no idea how to achieve this, or even where to begin looking.

Is there a known pattern/name for what I'm trying to achieve? Would anyone have any pointers on how to approach this? TIA for any help.

queen kestrelBOT
#

@fringe oar Here's a shortened URL of your playground link! You can remove the full link from your message.

dibbo.ie#0

Preview:```ts
const chain = () => {
const befores: Array<Function> = []
const afters: Array<Function> = []
let handler: Function = () => {}

const execute = async (event: any) => {
for (const before of befores) {
await before(event)
}
const res = awa
...```

wide dragon
#

your intuition is correct - once a type is declared/inferred, TS won't change it; you have to declare a new variable with a new type. simple example:

const x: { name?: string; age?: number } = {};
x.name = 'steve';
x.age = 45;
x; // x is has the same type as before

your use functions mutate the event, rather than return a new one. You'll either need to have them return a new object, or the mutated object as a new type.

for an intro pattern to doing this, see
https://github.com/type-challenges/type-challenges/blob/main/questions/00012-medium-chainable-options/README.md

GitHub

Collection of TypeScript type challenges with online judge - type-challenges/type-challenges

#

it's not precisely the same as what you're doing, but the same general pattern very much applicable to your case I think.