3
let payload = {
  item1: ["value1", "value2", "value3"],
  item2: [],
  item3: ["value4", "value5"]
}

Object.entries(payload).forEach(([key, values]) => {
if (values.length === 0) {
    // do this stuff

I'm getting an error that values is of type unknown. I'm not sure how to give it a type of array.

key will always be a string, and values will always be an array of strings.

4
  • 1
    Can you add a sample payload? Commented Nov 15, 2019 at 4:49
  • Good question, edited payload Commented Nov 15, 2019 at 4:56
  • 1
    interface Payload { item1: any; item2: any; item3: any } then, payload: Payload [] Commented Nov 15, 2019 at 5:02
  • Ah ok that makes sense. The items I get is random since its from an API call, how do i not hardcode it to 3 items? and I would just put string[] for an array of strings? Commented Nov 15, 2019 at 5:13

1 Answer 1

3

You can specify type of the key in an interface, so you wont be limited to a number.

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

const payload: Payload = {
    a: ['foo', 'bar'],
    b: [],
    c: ['baz']
};
Object.keys(payload).forEach((key, idx) => {
    if (payload[key].length === 0) {
    // do the stuff
}
});

Here's link to playground

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

1 Comment

Awesome thanks! I have to parse the payload, but I guess having a 2nd variable isn't too dirty. Will use this

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.