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);
};
}