【发布时间】:2021-08-19 15:02:55
【问题描述】:
这是一个后续问题: Javascript: How to convert a list of objects with many key-value pairs into one big nested object?
最初的目标是将具有许多键值对的对象列表转换为一个大的嵌套对象。
例如,从这个:
const items = [
{
"id": 3,
"orgId": 2,
"mod": "toyota",
"part": "wheel",
"price": 333
},
{
"id": 4,
"orgId": 2,
"mod": "toyota",
"part": "shell",
"price": 350
},
{
"id": 9,
"orgId": 2,
"mod": "honda",
"part": "wheel",
"price": 222
},
{
"id": 10,
"orgId": 2,
"mod": "honda",
"part": "shell",
"price": 250
}
]
并转换为:
items = {
"toyota": {"wheel": 333, "shell": 350 },
"honda": {"wheel": 222, "shell": 250 }
}
以下代码适用于 Javascript:
const transformedItems = items.reduce((acc, item) => {
acc[item.mod] = { ...acc[item.mod], [item.part]: item.price }
return acc
}, {})
console.log(transformedItems)
怎么样,我想把这个逻辑放到服务器端(用Typescript写的),代码编译不出来:
/Users/john/tmp/dolphin/api/node_modules/ts-node/src/index.ts:293
return new TSError(diagnosticText, diagnosticCodes)
^
TSError: ⨯ Unable to compile TypeScript:
src/utils/billingFunctions.ts:52:11 - error TS2538: Type 'null' cannot be used as an index type.
52 acc[item.mod] = { ...acc[item.mod], [item.part]: item.price }
~~~~~~~~~~~~~
src/utils/billingFunctions.ts:52:37 - error TS2538: Type 'null' cannot be used as an index type.
52 acc[item.mod] = { ...acc[item.mod], [item.part]: item.price }
~~~~~~~~~~~~~
src/utils/billingFunctions.ts:52:53 - error TS2464: A computed property name must be of type 'string', 'number', 'symbol', or 'any'.
52 acc[item.mod] = { ...acc[item.mod], [item.part]: item.price }
~~~~~~~~~~~~~~~
at createTSError (/Users/john/tmp/dolphin/api/node_modules/ts-node/src/index.ts:293:12)
at reportTSError (/Users/john/tmp/dolphin/api/node_modules/ts-node/src/index.ts:297:19)
at getOutput (/Users/john/tmp/dolphin/api/node_modules/ts-node/src/index.ts:399:34)
at Object.compile (/Users/john/tmp/dolphin/api/node_modules/ts-node/src/index.ts:457:32)
at Module.m._compile (/Users/john/tmp/dolphin/api/node_modules/ts-node/src/index.ts:530:43)
at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Object.require.extensions.<computed> [as .ts] (/Users/john/tmp/dolphin/api/node_modules/ts-node/src/index.ts:533:12)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
[nodemon] app crashed - waiting for file changes before starting...
但是,当我尝试时:
const transformedItems = items.reduce((acc, item) => {
console.log(acc, item.mod) // print out
acc[item.mod] = { ...acc[item.mod], [item.part]: item.price }
return acc
}, {})
控制台日志打印正常:item.mod 是一个字符串。
怎么会抱怨是Type 'null'?
【问题讨论】:
-
你能不能尝试给
array#reduce一个类型{} as {[key: string]: any}? -
你使用的是什么版本的 TypeScript?我看到了一个不同的错误。
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'.你所有的items看起来都是这样,还是缺少某些属性?
标签: typescript