Skip to content

Instantly share code, notes, and snippets.

@SiestaMadokaist
Created May 22, 2019 07:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SiestaMadokaist/a082cf44adcf8ad46430ae448f11b928 to your computer and use it in GitHub Desktop.
Save SiestaMadokaist/a082cf44adcf8ad46430ae448f11b928 to your computer and use it in GitHub Desktop.
FactoryType typescript
import Axios, { AxiosInstance } from 'axios';
abstract class BaseRequest {
abstract request(): AxiosInstance;
}
class Host1 extends BaseRequest {
request(): AxiosInstance { throw new Error('not implemented'); }
// todo
buyProduct() {
return this.request().post('...');
}
}
class Host2 extends BaseRequest {
request(): AxiosInstance { throw new Error('not implemented'); }
// todo
getItem() {
return this.request().post('....');
}
}
export enum AXIOSES {
HOST1 = 'HOST1',
HOST2 = 'HOST2',
}
export type RequestType<X extends keyof typeof AXIOSES> =
X extends AXIOSES.HOST1 ? Host1 :
X extends AXIOSES.HOST2 ? Host2 : BaseRequest;
export class AxiosFactory {
static get<K extends keyof typeof AXIOSES>(name: K): RequestType<K> {
if (name === AXIOSES.HOST1) {
return new Host1() as RequestType<K>;
// acceptable casting
} else if (name === AXIOSES.HOST2) {
return new Host2() as RequestType<K>;
}
throw new Error(`name not recognized ${name}`);
}
}
const a = AxiosFactory.get(AXIOSES.HOST1);
const b = AxiosFactory.get(AXIOSES.HOST2);
a.buyProduct(); // typecheck
b.getItem(); // typecheck
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment