2

I'm working with TypeScript, and I want to create an interface or type for a MyClass class. I want to be able to type the input parameters of the methods of MyClass, so I implement a BaseClass, which uses some types for input and output values. The issue is that, when hovering the parameters of the methods of myClass, —myString at MyClass methodOne, for example—, the type is any, while it should be string.

type ComplexObject1 = {
  myString: string;
};

type ComplexObject2 = {
  myNumber: number;
};

interface BaseClass {
  methodOne: (params: ComplexObject1) => number;
  methodTwo: (params: ComplexObject2) => string;
}

class MyClass implements BaseClass {
  methodOne({ myString }) {
    return myString.length;
  }
  methodTwo({ myNumber }) {
    return String(myNumber);
  }
}

I tried also setting BaseClass as interface or abstract class, or with the methods with different syntax, with same results:

type BaseClass = {
  methodOne: (params: ComplexObject1) => number;
  methodTwo: (params: ComplexObject2) => string;
};

or

abstract class BaseClass {
  methodOne: (params: ComplexObject1) => number;
  methodTwo: (params: ComplexObject2) => string;
}

or

interface BaseClass {
  methodOne(params: ComplexObject1): number;
  methodTwo(params: ComplexObject2): string;
}

What I am doing wrong here?

EDIT: this question was proposed as an answer: Typescript: Use class as interface It is an interesting read, but it doesn't answer the question of how to type the input params of each method.

EDIT2: This is the only solution I can think of, but is not satisfactory; I was expecting using an abstract class or an interface to implement/extend instead of separate function types:

type ComplexObject1 = {
  myString: string;
};

type ComplexObject2 = {
  myNumber: number;
};

type MyClassMethodOne = (params: ComplexObject1) => number;
type MyClassMethodTwo = (params: ComplexObject2) => string;

class MyClass {
  methodOne: MyClassMethodOne = ({ myString }) => {
    return myString.length;
  };
  methodTwo: MyClassMethodTwo = ({ myNumber }) => {
    return String(myNumber);
  };
}
Emille C.
  • 562
  • 1
  • 7
  • 23
  • Does this answer your question? [Typescript: Use class as interface](https://stackoverflow.com/questions/47114181/typescript-use-class-as-interface) – Tomas Feb 16 '21 at 07:49
  • Lots of thanks @ArtemeeSenin. Really interesting, but it doesn't focus on how to type the input params of the methods of the class from an abstract class/interface/type – Emille C. Feb 16 '21 at 08:00
  • That's a good question, all the examples I ve seen they redeclare the types. – Georgios Kampitakis Feb 16 '21 at 08:30

0 Answers0