Typescript Array Example

You can create arrays in Typescript quite simply:

let range: number[];
range = [1, 2];

You can do some quite novel things as well, such as to set the object to a range of types:

let range: number[] | string[];
range = [1, 2];
range = ['a', 'b'];

for (let i = 0; i < range.length; i++) {
  console.log(range[i].toString());
}

If you want to "cast" the value, you can also do it with an if statement around the item:

for (let i = 0; i < range.length; i++) {
  let listVal = range[i];
  if (typeof listVal === "number") {
    console.log(listVal + 1);
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *