Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix exercise 2 and add exercise 3 in chapter 8 #3

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

kimamula
Copy link
Contributor

@kimamula kimamula commented Dec 22, 2019

Thanks for the great book.

I fixed 2 problems in the answers of the exercises of chapter 8.

1. Fix onmessage compilation error

The current onmessage implementation in the answer of the exercise 2 does not compile.

image

I implemented handle method in which switch is used for type refinement and created Data type which takes advantage of distributive conditional type to declare more appropriate type than {command: C; args: MatrixProtocol[C]['in']} for data.

2. Add an answer for the exercise 3

Added code similar to the worker thread example.
By the way, though it is described that child_process is the way to do multithreading in Node.js, it is actually for multi processing.
Node.js provides worker_threads module for multithreading.

Other thing to note

This is not a problem in exercises, but the SafeEmitter implementation in chapter 8 does not compile.

image

What about using interface instead of class?

interface SafeEmitter<
  Events extends Record<PropertyKey, unknown[]>
> {
  emit<K extends keyof Events>(
    channel: K,
    ...data: Events[K]
  ): boolean
  on<K extends keyof Events>(
    channel: K,
    listener: (...args: Events[K]) => void
  ): this
  on(
    channel: never,
    listener: (...data: unknown[]) => void
  ): this
}
let commandEmitter: SafeEmitter<Commands> = new EventEmitter()

Not only does this compile, but also this is more lightweight as this is a type-level wrapper and does not emit any JavaScript code.

@kimamula kimamula changed the title fix exercise 2 and add exercise 3 fix exercise 2 and add exercise 3 in chapter 8 Dec 22, 2019
@kimamula
Copy link
Contributor Author

TS playground link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant