簡體   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