![](/img/trans.png)
[英]How to declare a specific type of empty array inside a object using typescript?
[英]How to declare types for empty object array with typescript?
假设数组是const items = [{category:'cat1', name:'name1'},{category:'cat2', name:'name2'}]
。
我想将上面的数组构造成一个对象格式,如下所示:
{
'cat1':'name1',
'cat2':'name2'
}
没有打字稿,我可以执行以下操作来解决问题:
const parseFunction = (items) => {
const newObj = {};
for (const item of items) {
newObj[item.category] = newObj[item.name];
}
return newObj;
}
但是下面的打字稿:
interface IItems{
category: string,
name: string
}
interface INewObj{
'cat1': string,
'cat2': string
}
const parseFunction = (items: IItems[]) => {
const newObj = {} as INewObj;
for (const item of items) {
newObj[item.category] = newObj[item.name];
}
return newObj;
}
行newObj[item.category] = newObj[item.name]
抛出以下 TS 错误
Element implicitly has an 'any' type because expression of type 'number' can't be used to index type 'IQuotaByCategory'.
No index signature with a parameter of type 'number' was found on type 'IQuotaByCategory'.ts(7053)
我应该如何解决这个问题?
使用Record<Keys, Type>来映射未知的键和值。
打字稿代码
const items: IItems[] = [{ category: 'cat1', name: 'name1' }, { category: 'cat2', name: 'name2' }];
interface IItems {
category: string,
name: string
}
type NewObjType = Record<string, string>;
const parseFunction = (items: IItems[]): NewObj => {
const newObj: NewObjType = {};
for (const item of items) {
newObj[item.category] = item.name;
}
return newObj;
}
console.log(parseFunction(items));
Javascript 代码段
"use strict"; const items = [{ category: 'cat1', name: 'name1' }, { category: 'cat2', name: 'name2' }]; const parseFunction = (items) => { const newObj = {}; for (const item of items) { newObj[item.category] = item.name; } return newObj; }; console.log(parseFunction(items));
PS:你在这里犯了一个小错误newObj[item.category] = newObj[item.name]
因为该值不存在于 newObj 变量中。 我已更改为正确的分配如下: newObj[item.category] = item.name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.