0

I got an error in my foreach with an array:

function setRowData({ json }: NewType): void {
    // foreach key and value in json object
    // fill into an object
    // add object to array
    let tableRows: { id: string; key: string; de: string; it: string; }[] = [];
    Object.entries(json).forEach(([key, value]) => tableRows.push({
        id: key, key: key, de: value, it: (typeof value === 'string' ? value : "")
    }));
    setTableData(tableRows);
}

The error occurs on the line with the following content: id: key, key: key, de: value, it: (typeof value === 'string' ? value : "")

Does anyone know why the value variable called value inside my array is undefined?

In addition I post a photo of it and where the error occurs: enter image description here

This one is the description of the foreach, why is the second type in the array undefined? enter image description here

5
  • How does NewType definition look like? Commented Mar 27, 2022 at 8:16
  • I suspect the issue is that the function param should be json instead of {json}. Commented Mar 27, 2022 at 8:19
  • @Clarity It should not be json because i need to get the correct values of my json and without the curly braces { } it won't be possible anymore... but of course this fixes the error but doesn't help anything more hahhaha Commented Mar 27, 2022 at 8:37
  • So does NewType have a property called json? Commented Mar 27, 2022 at 8:49
  • @Clarity yes like that: type NewType = { json: any; }; Commented Mar 27, 2022 at 10:37

1 Answer 1

2

When you use Object.entries() you extract an array of key-value tuples.

In this case the problem is that typescript cannot infer the type of values in the object, so it types it as unknown ([string, unknown][]).

object entries unknown

The error is telling you that you cannot assign unknown to string.

In order to have it typed as string you must either specify it when using Object.entries():

typed as string

const entries = Object.entries<string>(json);

Or you should specify in your NewType that json is an object with only string as values (using typescript's Record: Record<string, string>)

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

2 Comments

if I use entries instead of Object.entries with your defined variable, then I can't specify the other stuff like key, value anymore... :/
Ah thanks Sandro, now it works if i say json is an object with only string as value. As you said: json: Record<string, string>

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.