Home > Blockchain >  Can I describe class methods' arguments in a reusable way?
Can I describe class methods' arguments in a reusable way?

Time:10-19

Let's assume the following piece of code.

class MyClass {
  method1(arg1: string, arg2: number, arg3: number) {}
    
  method2(arg1: string, arg2: number, arg3: number) {}
}

I'd like to take the part that says arg1: string, arg2: number, arg3: number and express it in a way that I could reuse.
Hopefully the below example would make sense, even if it obviously doesn't work

interface MyClassMethodArgs {
  arg1: string;
  arg2: number; 
  arg3: number;
}

interface MyClass {
  // How can I express "arg1: string, arg2: number, arg3: number" as MyClassMethodArgs?
  method1(arg1: string, arg2: number, arg3: number): void;
  method2(arg1: string, arg2: number, arg3: number): void;
}

class MyClassImpl implements MyClass {
  // How can I inherit the types of MyClass without repeating them?
  method1(arg1, arg2, arg3) {}
    
  method2(arg1, arg2, arg3) {}
}

CodePudding user response:

You could do this:

type ThreeNumberFunction = (a: number, b: number, c: number) => void

class MyClass {
  method1: ThreeNumberFunction = (a, b, c) => {
    // ...
  };
  method2: ThreeNumberFunction = (a, b, c) => {
    // ...
  };
}

Unfortunately, this has the downside of creating new functions for each instance of the class, instead of looking up the methods on the class, so it may degrade performance and use more memory. Personally, unless the method signatures were very complicated, or I specifically needed the functions to be bound to the instance so I could pass around obj.method1 without having to call obj.method1.bind(obj), then I would just not worry about the small amount of duplication.

Also, note that you can't do the same thing using an interface, because parameter types are not inferred from the interface's method signatures:

interface MyInterface {
  method1: ThreeNumberFunction;
  method2: ThreeNumberFunction;
}

// parameters implicitly have type 'any'
class MyClass2 implements MyInterface {
  method1(a, b, c) {
    // ...
  }
  method2(a, b, c) {
    // ...
  }
}

Playground Link

  • Related