繁体   English   中英

如何使用打字稿声明空对象数组的类型?

[英]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)

我应该如何解决这个问题?

在实践中,我猜您不会真正知道类别是cat1cat2等,您只知道它们将是字符串。 因此, INewObj的定义需要更宽松一些。

type INewObj = {
  [key: string]: string
}

可以进一步缩短为Record<string, string>

游乐场链接

你可以更进一步,通过允许 Typescript 为你推断它来完全消除INewObj

游乐场 2

此解决方案能否满足您的需求?

使用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.

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