A
A
Alex Mirgorodskiy2020-09-17 09:14:03
typescript
Alex Mirgorodskiy, 2020-09-17 09:14:03

How to describe an array containing an array of instances from a class in typescript?

Good day to all, I’m just entering TypeScript, I seem to understand the base, but I still can’t understand and google more complex moments.

Let's say I have a class

class TableSelection {
  static selectedClass: string = 'selected'
  group: object[]

  constructor() {
    this.group = []
  }

  select($cell) {
    this.clear()
    this.group.push($cell)
    $cell.addClass(TableSelection.selectedClass)
  }

  clear() {
    this.group.forEach(($selectedCell) => $selectedCell.removeClass(TableSelection.selectedClass))
    this.group = []
  }
}


In it, I described that I would have an array of objects this.group (Class instances with their methods), and when I start iterating over this array in the clear method and calling methods of class instances, TypeScript tells me that the object type does not have such methods. As I understand it, I need to describe either from which class the instances will lie there, or describe the methods that will be in this object. Please tell me how to describe such structures correctly

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex, 2020-09-17
@AlexWeb6667

Well, if it's just like a textbook, then you need to describe the interface that the class will depend on TableSelection(one class should not directly depend on another, since it is more difficult to maintain).
For example like this:

interface Cell {
    addClass(cssClass: string) : void
    removeClass(cssClass: string) : void
}

class TableSelection {
...

Well, then you just specify that the property groupis an array of anything that matches the interfaceCell
interface Cell {
    addClass(cssClass: string) : void
    removeClass(cssClass: string) : void
}

class TableSelection {
  static selectedClass: string = 'selected'
  group: Cell[]

  constructor() {
    this.group = []
  }

  select($cell: Cell) {
    this.clear()
    this.group.push($cell)
    $cell.addClass(TableSelection.selectedClass)
  }

  clear() {
    this.group.forEach(($selectedCell) => $selectedCell.removeClass(TableSelection.selectedClass))
    this.group = []
  }
}

Finished code example

A
acwartz, 2020-09-17
@acwartz

if working with the DOM, not with classes, then use the any type instead of the object type.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question