0

My web service returns an array of objects that looks like this:

[ 
  {
   "abc": "test 1"
  },
  {
   "def": "test 2"
  },
  {
   "ghi": "test 3"
  }
]

Now I want to declare a TypeScript interface for this result. But I have no idea how to do that because the key of each object can be string whose name varies.

Specifically:

  • An object has exactly one property.
  • The key of that property can have any name.
  • The value of the property is a string.
3
  • which means Object[] ? Commented Jan 26, 2021 at 13:33
  • It may be possible to write a more specific type for this, but we don't have enough details to say so with accuracy. Which parts of the example you gave can vary and which are fixed? Are the keys always those three? Do the objects always have exactly one key? Are the values in the objects always strings? Try to post a specification of the type in plain English as part of your question, and then maybe someone can come along and turn that into Typescript. Commented Jan 26, 2021 at 13:35
  • In the TypeScript Handbook, see Indexable Types. Commented Jan 29, 2021 at 20:16

2 Answers 2

3

From the code you provided, I suggest using:

const a: { [key: string]: string }[] = [ 
  {
   "abc": "test 1"
  },
  {
   "def": "test 2"
  },
  {
   "ghi": "test 3"
  }
]

It is a string indexed object with string values.

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

1 Comment

Could also use Record<string, string>[]
1

Probably not the best solution, just in case if you want interface strictly:

interface webResponse{
    [key: string]: string;
}

let myvalue= new Array<webResponse>();

myvalue[0] = {["asdas"]: 'qwerty'};
myvalue[1] = {["asdas2"]: 'qwerty2'};

you can iterate over myvalue with simple for..in.

Comments

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.