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?

10
  • 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. Commented Dec 18, 2017 at 21:35
  • string[] only defines what type the variable is. It doesn't assign anything to it. Commented Dec 18, 2017 at 21:36
  • 2
    results['searchCaption'] = ""; is not a valid array syntax. Arrays are index based - objects are key based. Commented Dec 18, 2017 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! Commented Dec 18, 2017 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. Commented Dec 18, 2017 at 21:39

1 Answer 1

9

What you want is this:

let results = new Array<string>();
results['searchCaption'] = '';
Sign up to request clarification or add additional context in comments.

1 Comment

I will accept the answer though there seems to be an anti-pattern about the use of arrays this way I came to know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.