Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

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

Typescript: discriminating worker #1301

Closed
xxRockOnxx opened this issue Jul 2, 2022 · 0 comments
Closed

Typescript: discriminating worker #1301

xxRockOnxx opened this issue Jul 2, 2022 · 0 comments

Comments

@xxRockOnxx
Copy link

xxRockOnxx commented Jul 2, 2022

This is more of a Typescript question but how do I strongly-type Worker?

Here's a minimal reproduction:

interface JobData {
  id: string
}

interface FooData extends JobData {
  foo: string
}

interface BarData extends JobData {
  bar: boolean
}

type FooWorker = Worker<FooData, string, 'foo'>
type BarWorker = Worker<BarData, boolean, 'bar'>

const fooBarWorker: FooWorker | BarWorker = new Worker('worker', async (job) => {
  switch (job.name) {
    case 'foo':
      console.log(job.data.foo) // Error: Property `foo` does not exists on type `JobData`
      return job.data.foo
    case 'bar':
      console.log(job.data.bar) // Error: Property `bar` does not exists on type `JobData`
      return job.data.bar
  }
})

Using & instead of | somehow works but only for one type of worker

const fooBarWorker: FooWorker & BarWorker = new Worker('worker', async (job) => {
  switch (job.name) {
    case 'foo':
      console.log(job.data.foo)
      return job.data.foo

    // Error: Type 'bar' is not comparable to type 'foo'
    case 'bar':
      console.log(job.data.bar)
      return job.data.bar
  }
})

Related: #1156
Minimal reproduction: https://codesandbox.io/s/typescript-playground-export-forked-cmr7k2?file=/index.ts

@taskforcesh taskforcesh locked and limited conversation to collaborators Jul 7, 2022
@manast manast converted this issue into discussion #1310 Jul 7, 2022

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant