Skip to content

Instantly share code, notes, and snippets.

@CodeDaraW
Last active July 8, 2019 11:53
Show Gist options
  • Save CodeDaraW/4228843ce9d7d402d0c88d3041d4bd30 to your computer and use it in GitHub Desktop.
Save CodeDaraW/4228843ce9d7d402d0c88d3041d4bd30 to your computer and use it in GitHub Desktop.
// LeetCode Hire Writeup
interface Action<T> {
payload?: T;
type: string;
}
class EffectModule {
count = 1;
message = "hello!";
delay(input: Promise<number>) {
return input.then(i => ({
payload: `hello ${i}!`,
type: 'delay'
}));
}
setMessage(action: Action<Date>) {
return {
payload: action.payload!.getMilliseconds(),
type: "set-message"
};
}
}
type FuncName<T> = { [P in keyof T]: T[P] extends Function ? P : never }[keyof T];
type ParamType<T> = T extends (param: infer P) => any ? P : T;
type PromiseType<T> = T extends Promise<infer U> ? U : T;
type PickParam<T> = T extends Promise<infer U> ? U : (T extends Action<infer V> ? V : T);
type Connect = (module: EffectModule) => {
[T in FuncName<EffectModule>]: (x: PickParam<ParamType<EffectModule[T]>>) => PromiseType<ReturnType<EffectModule[T]>>
};
const connect: Connect = m => ({
delay: (input: number) => ({
type: 'delay',
payload: `hello ${input}`
}),
setMessage: (input: Date) => ({
type: "set-message",
payload: input.getMilliseconds()
})
});
type Connected = {
delay(input: number): Action<string>;
setMessage(action: Date): Action<number>;
};
export const connected: Connected = connect(new EffectModule());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment