我正在尝试将一种 Record 类型映射到 Typescript 中的一种新类型。到目前为止,这是我所拥有的,但这似乎不是使用地图创建记录的正确方法。
有什么建议吗?
const data: Record<string, string> = { "test": : "Test", "test2": "Test2"}
const result = Object.keys(data).map((i): Record<string, string> => [i, data[i]])
编辑:
这是输入:
const data: Record<string, CustomType> = { "Option 1": {"id": "123"}, "Option 2": {"id": "987"}}
const data_two: Record<string, CustomType> = { "Option 1": {"id": "567"}, "Option 2": {"id": "376"}}
这是我的预期输出:
一个 Record<string, string[]
看起来像:
{ "Option 1": ["123", "567"], "Option 2": ["987", "376"] }
答案 0 :(得分:1)
你需要
(1) 先在 JavaScript 中实现逻辑
(2) 为 TypeScript 正确键入 JavaScript。将输出对象类型声明为 { [K in keyof typeof data]: string[] }
即可获得所需的结构。
type CustomType = { id: string };
const data: Record<string, CustomType> = { "Option 1": {"id": "123"}, "Option 2": {"id": "987"}}
const data_two: Record<string, CustomType> = { "Option 1": {"id": "567"}, "Option 2": {"id": "376"}}
const output: {
[K in keyof typeof data]: string[]
} = Object.fromEntries(
Object.keys(data).map(key => [key, []])
);
for (const obj of [data, data_two]) {
for (const [key, customType] of Object.entries(obj)) {
output[key].push(customType.id)
}
}