![](/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.