Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear a typed array in typescript and preserving its type?

Now in a class, I declared an array with type: CustomType, like below

class Example {
  public exampleArray: CustomType[];
  public clearArray() {
    this.exampleArray = [];
  }
}

As you can see the clearArray assign an UNDEFINED type of an empty array, which seems lost the type information.

How I can clear the array but preserving its declared type?

like image 239
Vincent-cm Avatar asked Sep 28 '18 10:09

Vincent-cm


1 Answers

There can be 3 ways of emptying an array

  1. setting its length = 0

    myArr.length = 0;

  2. using splice method Array

    myArr.splice(0,myArr.length);

  3. Pop() each element of array

    while(myArr.length){
      myArr.pop();
    }    
    
like image 193
Sarthak Aggarwal Avatar answered Sep 21 '22 16:09

Sarthak Aggarwal