【发布时间】:2018-08-11 23:46:41
【问题描述】:
所以,我有一个(非常非常)大的对象,我希望有一个函数可以接收任何对象 (T) 及其键列表(K 扩展 keyof T)并返回一个新对象只有那些传入的键/值。本质上是 {[key: K]: string}。
这里是有问题的函数:
export function mapResources(resources, keys: string[]) {
return keys.reduce((response, key) => ({
...response,
[key]: resources[key]
}), {});
}
我一直在尝试写这个函数的类型定义,但是在TS1023: An index signature parameter type must be 'string' or 'number'.下失败了
export function mapResources<K extends keyof IResources>(resources: IResources, keys: K[]): {[key: K]: IResources[K]} {
return keys.reduce((response, key) => ({
...response,
[key as string]: resources[key]
}), {});
}
我的目标是获取该子集对象,并让我的 IDE(和打字稿)根据传入的内容了解对象的外观。我已经有了资源类型。可能有一种与我在这里开始的方式完全不同的方法,我只是不确定如何开始输入这个。
【问题讨论】:
-
是你想要做的事情,比如获取一个对象 {a: 1, b: 2, c: 3, d: 4, e: 5} 并通过传递一个列表像 ['b', 'c', 'e'] 这样的键,制作原始对象的精简副本,如 {b: 2, c: 3, e: 5}?
-
是的。正是这个。
标签: typescript typescript-typings