bcherny / bcherny/programming-typescript-answers

Chapter 8's RedisClient example

Open
#9 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
555
Forks
154
PR merge metrics
No merged PRs in 30d

Description

In chapter 8 (_Async Streams_ >> _Event Emitters_, on pages 185-186) you have defined the following two types:
```ts
type Events = {    
ready: void    
error: Error    
reconnecting: {
delay: number, 
attempt: number
}
}

type RedisClient = {    
on(event: E, f: (args: Events[E]) => void): void
}
```

I would like to have a naive implementation like this:
```ts
let Client: RedisClient = {        
on(event: E, f: (args: Events[E]) => void) {
        if(event === "reconnecting") {
           f({delay: 1, attempt: 1})
     }    
}
}
Client.on("reconnecting", (param :{delay: number, attempt: number}) => console.log(param.delay))
```
Unfortunately it gives me the following error (at this `f({delay: 1, attempt: 1})` line):
```
Argument of type '{ delay: number; attempt: number; }' is not assignable to parameter of type 'Events[E]'.
Type '{ delay: number; attempt: number; }' is not assignable to type 'void & Error & { delay: number; attempt: number; }'.
Type '{ delay: number; attempt: number; }' is not assignable to type 'void'.(2345)
```
It seems like it uses intersection instead of union. How can I fix this?

I've found a related [Typescript issue](https://github.com/microsoft/TypeScript/issues/31904), but I couldn't manage to apply the suggested workaround in this example. Can you help me with this please?

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.