lzszone
lzszone

Reputation: 75

Typescript: Specifying a type for an instance method

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?

Upvotes: 1

Views: 52

Answers (1)

Karol Majewski
Karol Majewski

Reputation: 25790

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 => {
    /* ... */
  }
}

Upvotes: 1

Related Questions