I have this base class:
export class ActVsBudget {
constructor(
public budget?: number,
public actual?: number,
public monthDiff?: number,
public cumBudget?: number,
public cumActual?: number,
public cumDiff?: number
) {}
}
And this extended class:
export class CostOverview extends ActVsBudget {
constructor(
public plant?: Plant,
public plantArea?: PlantArea,
public costCenter?: CostCenter,
public costAccType?: CostAccountingType,
public year?: number,
public month?: number
) {
super();
}
}
Now, I want a function, which takes a parameter (an array) of any class, which extends the above base class.
With this function signature I can pass the above CostOverview
class as a parameter because of the inheritance:
calculateSums(data: ActVsBudget[])
But then what if I need access to any other property of the child class. I can't have acces these properties with this signature.
I tried something like this:
calculateSums(data: <T extends ActVsBudget>[])
But ts complains, that I need some brackets before the [
.
What would be the right function signature?
Thanks.
CodePudding user response:
You have you generic definition wrong: :
calculateSums<T extends ActVsBudget>(data: T[]) {
...
}
CodePudding user response:
First, you should know that you can not define a type like this:
calculateSums(data: <T extends ActVsBudget>[])
Instead, you should use and define your type before parentheses like:
caculateSums<TYPE extends ActVsBudget>(data: TYPE[]);
When you want to use it you should do something like using other properties of the new inherited class. SomeClass
in example
class SomeClass extends ActVsBudget {}
const similarData = [new SomeClass(), new SomeClass()];
calculateSums<SomeClass>(similarData);