1

here I define the variable results to be an array of strings:

let results: string[]; 

and here below, I assign a value to kick things off:

results['searchCaption'] = "";

and then, the show stops with ERROR TypeError: Cannot set property 'searchCaption' of undefined

What am I missing here? Do I need to define an interface for it first?

Average Joe
  • 4,521
  • 9
  • 53
  • 81
  • 1
    Did you initialize the array? IE: `let results: string[] = []`? It would appear from the error that results is undefined, indicating that you never assigned anything to it. – CRice Dec 18 '17 at 21:35
  • `string[]` only defines what type the variable is. It doesn't assign anything to it. – JJJ Dec 18 '17 at 21:36
  • 2
    `results['searchCaption'] = "";` is not a valid array syntax. Arrays are index based - objects are key based. – tymeJV Dec 18 '17 at 21:37
  • Perfect pointer! Sure that is it. All along, I was thinking that `let results: string[]; ` would kicks things off with results = [] anyway! I think in ASP, it was not the case, my memory mislead me. Thank you! CRice! – Average Joe Dec 18 '17 at 21:37
  • Happy to help, but per @tymeJV's comment, you're assigning things to the array as though it were an object, which while possible, is definitely an anti-pattern. – CRice Dec 18 '17 at 21:39
  • tymeJV, that is a valid syntax; for 2 reasons: 1) typeScript tslint allows it. 2) when I did the init with `results = [];`, it does take it and I'm done with it. – Average Joe Dec 18 '17 at 21:40
  • did not know about the anti-pattern on this. so there is no such thing as ASSOCIATE ARRAYS like concept in typescript? No multidimensional arrays neither? Does that mean build all structures involving keys around JSON? Just got curious; do you happen to know why this would be an anti-pattern? – Average Joe Dec 18 '17 at 21:43
  • It's valid the same way that it's valid to use strings to store numbers – that is, the language specification doesn't stop you from doing it, but you're still using the wrong data type for the job. You end up with an empty array with a custom property. – JJJ Dec 18 '17 at 21:44
  • You might be interested in [this question](https://stackoverflow.com/questions/874205/what-is-the-difference-between-an-array-and-an-object). And, based on the misuse of "JSON", [this question too](https://stackoverflow.com/questions/3975859/what-are-the-differences-between-json-and-javascript-object). – JJJ Dec 18 '17 at 21:45
  • JJJ thank you for the link. It will shed enough light for me. – Average Joe Dec 18 '17 at 21:47

1 Answers1

8

What you want is this:

let results = new Array<string>();
results['searchCaption'] = '';
David Anthony Acosta
  • 4,766
  • 1
  • 19
  • 19
  • I will accept the answer though there seems to be an anti-pattern about the use of arrays this way I came to know. – Average Joe Dec 18 '17 at 22:38