[Typescript] Generic slots, using built-in types as much as possible

发布时间 2023-04-10 21:22:54作者: Zhentiw

There are two options doing the same things.

const makeSafe =
  <TParams extends any[], TReturn>(func: (...args: TParams) => TReturn) =>
  (
    ...args: TParams
  ):
    | {
        type: "success";
        result: TReturn;
      }
    | {
        type: "failure";
        error: Error;
      } => {
    try {
      const result = func(...args);

      return {
        type: "success",
        result,
      };
    } catch (e) {
      return {
        type: "failure",
        error: e as Error,
      };
    }
  };

 

Option2:

const makeSafe =
  <TFunc extends (...args: any[]) => any>(func: TFunc) =>
  (
    ...args: Parameters<TFunc>
  ):
    | {
        type: "success";
        result: ReturnType<TFunc>;
      }
    | {
        type: "failure";
        error: Error;
      } => {
    try {
      const result = func(...args);

      return {
        type: "success",
        result,
      };
    } catch (e) {
      return {
        type: "failure",
        error: e as Error,
      };
    }
  };

 

Both options provide a similar implementation for the makeSafe function, but they differ in their typing. Option 2 is more concise and considered better because it uses built-in TypeScript utility types Parameters and ReturnType to infer the argument types and return type of the given function func. This makes the code easier to read and understand.

I recommend going with Option 2 for its cleaner and more concise typing.