0

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.

1
  • calculateSums<T extends ActVsBudget>(data: T[]) Commented Feb 13, 2022 at 14:59

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

You have you generic definition wrong: :

calculateSums<T extends ActVsBudget>(data: T[]) {
 ...
}

Documentation

Comments

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.