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

More useful type definition #192

Closed
lacolaco opened this issue Dec 4, 2018 · 1 comment
Closed

More useful type definition #192

lacolaco opened this issue Dec 4, 2018 · 1 comment

Comments

@lacolaco
Copy link
Contributor

lacolaco commented Dec 4, 2018

Currently, Comlink.proxy returns just Function type. It is not useful because any language services or editors cannot suggest await new Foo() interface.

My proposal is to define a type of Comlink.proxy function, called PromisedConstructor.

type Promised<T> = {
  [P in keyof T]: T[P] extends (...args: infer A) => infer R
  ? (...args: A) => Promise<R>
  : Promise<T[P]>
};
type PromisedConstructor<T>  = {
  new(...args: any): Promise<Promised<T>>;
};

TypeScript Playground

Usecase (w/ Angular)

import { Injectable } from '@angular/core';
import * as Comlink from 'comlinkjs';
type LoggerType = import('./logger').Logger; // import only types

type Promised<T> = {
  [P in keyof T]: T[P] extends (...args: infer A) => infer R
  ? (...args: A) => Promise<R>
  : Promise<T[P]>
};
type PromisedConstructor<T>  = {
  new(...args: any): Promise<Promised<T>>;
};

const LoggerProxy = Comlink.proxy(
  new (Worker as any)('./logger', { type: 'module' }) // global `Worker` workaround...
) as PromisedConstructor<LoggerType>;

@Injectable({
  providedIn: 'root'
})
export class LoggerService {
  async sendLog(value: any) {
    const logger = await new LoggerProxy(); // type safe
    await logger.log(value); // type-safe
  }
}

I've not found out yet how to extract the original constructor's arguments type. With the above type definition, await new LoggerProxy() 's constructor arguments are all recognized as any[].

Thanks.

@lacolaco
Copy link
Contributor Author

lacolaco commented Dec 7, 2018

Solved in v3.1. Thanks!

@lacolaco lacolaco closed this as completed Dec 7, 2018
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

No branches or pull requests

1 participant