【问题标题】:What would the type definition look like for a function that returns an object that is a subset of an original object对于返回作为原始对象子集的对象的函数,类型定义会是什么样子
【发布时间】: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


【解决方案1】:

你已经很接近了;您正在寻找mapped types,它允许您迭代键(而不是使用索引器)。也就是说,不要使用这个:

{[key: K]: IResources[K]}

改用这个:

{[P in K]: IResources[P]}

事实上,这是一个足够有用的构造,它以Pick&lt;T,K&gt; 的形式存在于standard library 中:

Pick<IResources, K>

所以你的函数变成这样:

export function mapResources<K extends keyof IResources>(resources: IResources, keys: K[]): Pick<IResources, K> {
  return keys.reduce((response, key) => ({
      ...response,
      [key as string]: resources[key]
  }), {});
}

这将无法在实现中进行类型检查,因为我认为 TypeScript 不理解 Pick&lt;IResources, K&gt; 上的传播类型。如果您确定实现中的一切正常,您可以使用any 断言来提供帮助:

export function mapResources<K extends keyof IResources>(resources: IResources, keys: K[]): Pick<IResources, K> {
  return keys.reduce((response, key) => ({
      ...(response as any),
      [key]: resources[key]
  }), {});
}

您可以验证其行为是否符合要求(如果不知道IResources 是什么,我将无法轻松做到这一点)。希望有帮助;祝你好运!

【讨论】:

  • response as any 和我自己发现的一样。这就是解决方案,您和我在同一时间发布!
  • 我想我正在学习一些我没有意识到 TypeScript 可以做到的新东西。那么这是否意味着像这样的类型:type Keys = 'option1' | 'option2' 既可以被视为只允许这两个字符串的类型,又可以被视为这两个字符串的常量数组?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-11
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多