1

I'm using Typescript 3.3. There is a type from a library: type Fn = (arg0: t1...) => any, and I imported it, want to use it to sign an instance method:

class A {
  mtd() {} // to be signed
}

How should I do?

1 Answer 1

1

If your intention is to reuse the type signature of Fn in order to avoid repetition, you can do that, but the method will depend on whether mtd must be a proper method or an arrow function assigned to a class property.

Class methods and function properties are not the same. They differ in terms of handling this, which makes property functions incompatible with inheritance. Proceed with caution.

Class method

type Fn = (argument: string) => any;

interface IA {
  mtd: Fn;
}

class A implements IA {
  /**
   * Parameter types must be repeated 😞 but they will be type-checked as expected.
   */
  mtd(argument: string) {
    /* ... */
  }
}

Arrow function property

type Fn = (argument: string) => any;

class A {
  /**
   * We know `argument` is a `string.
   */
  mtd: Fn = argument => {
    /* ... */
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This answer changes the method on the class prototype to a separate function-valued property on each instance... and as an arrow function it also loses the this context. That might be acceptable, but the difference should probably be noted.
@jcalz you're right, the difference should be made explicit. I have updated my answer. Thank you for noticing that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.