[英]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?有谁知道为什么我的数组中名为value
的value
变量未定义?
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
作为值(使用打字稿的Record
: Record<string, string>
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.