简体   繁体   English

数组中的值未定义 TypeScript

[英]Value in Array is undefined TypeScript

I got an error in my foreach with an array:我的 foreach 中有一个数组错误:

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: "")错误出现在内容如下的行: 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?有谁知道为什么我的数组中名为valuevalue变量未定义?

In addition I post a photo of it and where the error occurs:另外我贴了一张它的照片和错误发生的地方: 在此处输入图像描述

This one is the description of the foreach, why is the second type in the array undefined?这个是foreach的描述,为什么数组中的第二个类型是undefined? 在此处输入图像描述

When you use Object.entries() you extract an array of key-value tuples.当您使用Object.entries()时,您会提取一个键值元组数组。

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][] ).在这种情况下,问题是 typescript 无法推断 object 中值的类型,因此它将其键入为unknown ( [string, unknown][] )。

对象条目未知

The error is telling you that you cannot assign unknown to string .该错误告诉您不能将unknown分配给string

In order to have it typed as string you must either specify it when using Object.entries() :为了将其输入为string ,您必须在使用Object.entries()时指定它:

输入为字符串

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> )或者你应该在你的NewType中指定 json 是一个 object 只有string作为值(使用打字稿的RecordRecord<string, string>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM