34

I would like to have an array that holds string error messages. Here's the code that I came up with:

var errors: [string];
errors = [];
Object.keys(response.data.modelState).forEach(function (key) {
    errors.push.apply(errors, response.data.modelState[key]);
});

I tried some different ways to add a typescript definition to the variable errors but none seem to work for this case. The first definition works okay but then when I am pushing values I need to push to an array and when I set:

errors = []; 

Then it gives me an error message:

Severity Code Description Project File Line Error TS2322 Type 'undefined[]' is not assignable to type '[string]'. Property '0' is missing in type 'undefined[]'. Severity Code Description Project File Line Error Build: Type 'undefined[]' is not assignable to type '[string]'.

  • Does this answer your question? [TypeScript: Creating an empty typed container array](https://stackoverflow.com/questions/15826745/typescript-creating-an-empty-typed-container-array) – user202729 Aug 15 '21 at 02:20

4 Answers4

35

The definition of string array should be:

// instead of this
// var errors: [string];
// we need this
var errors: string[];
errors = [];

Note: another issue could be the parameter key here

...forEach(function (key) {...

I would guess that we often should declare two of them, because first is very often value, second key/index

Object.keys(response.data.modelState)
      .forEach(function (value, key) {
    errors.push.apply(errors, response.data.modelState[key]);
});

And even, we should use arrow function, to get the parent as this

Object.keys(response.data.modelState)
      .forEach( (value, key) => {
    errors.push.apply(errors, response.data.modelState[key]);
});
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
16

Outside of a method:

arr: string[] = [];
Gero
  • 12,993
  • 25
  • 65
  • 106
13

Missing an obvious answer, needed when not assigning it to a variable: [] as string[]

wvdz
  • 16,251
  • 4
  • 53
  • 90
0

An alternative is to set the length to 0:

const myArray = [1, 2, 3, 4]
myArray.length = 0

This makes it possible to use const in contexts where emptying the array is needed.

Anders Zommarin
  • 7,094
  • 2
  • 25
  • 24