0

I have the following method:

public test(keyValue : { [index:string] : string} ){
 ...
}

How can I modify the signature so that keyValue (array filled with strings) shall have an index of type string but after that I can use this still as an array (filled also with strings) in something like that (maybe this syntax is also wrong for using key AND value?):

keyValue.forEach(key, value => {
    //key is string
    //value is string
});
1
  • string[] & { [s: string]: string}; should work but an array literal will not be assignable to it so it is of limited value. What is it you are trying to achieve? Commented Aug 21, 2019 at 9:41

1 Answer 1

3

It looks like you misunderstood the Typescript index signature principle. When you're typing keyValue : { [index:string] : string} you're actually not defining an array at all. You're defining the default signature (~structure) of a Typescript object.

Thus the prototype you've written will accept any object with a string as a key, and a string as a value, eg:

{
  "keyOne": "valueOne",
  "keyTwo": "valueTwo"
}

In order to iterate over the pairs stored in your object, you can then:

for (let [key, value] of Object.entries(keyValue)) {
  /* Do something... */
}

I invite you to take a look at this stackblitz example I've created to illustrate it. Be careful that indicating an index signature such as the one you proposed does not ensure that the given object passed as argument will match (no error will be thrown at runtime).

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, that does the job, only one thing left: If I want to declare an array with strings in it and with a string typed index, how would the syntax look like in typescript? - Thats not so easy to google as I thought because all I got was this object style approach found in my original post
I'm afraid that an Array can't do what you're asking for. According to MDN documentation Each item in an array has a number attached to it, called a numeric index, that allows you to access it. In JavaScript, arrays start at index zero and can be manipulated with various methods.

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.