Created
May 22, 2019 07:33
-
-
Save SiestaMadokaist/a082cf44adcf8ad46430ae448f11b928 to your computer and use it in GitHub Desktop.
FactoryType typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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