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);
  };
}
3
  • Does this answer your question? Typescript: Use class as interface Commented Feb 16, 2021 at 7: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 Commented Feb 16, 2021 at 8:00
  • That's a good question, all the examples I ve seen they redeclare the types. Commented Feb 16, 2021 at 8:30

0

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.