首页 > 解决方案 > 打字稿从字典和键列表构造一个子字典

问题描述

我正在尝试从字典和键列表创建一个子字典。

type MyDictElementType = {
  x: number
}
type MyDictType = {
  [key: string]: MyDictElementType
}

const myKeys: string[] = ['a']
const myDict: MyDictType = { 'a': {x: 0}, 'b': {x: 1} }

const createSubDictionary = (fullDictionary: MyDictType, searchKeys: string[]) => {
  const newDict: MyDictType = {}
  searchKeys.map((searchKey) => {
    newDict[searchKey] = fullDictionary[searchKey]
  })
  return newDict
}

newDict有没有一种纯粹的函数式方法可以在没有局部变量的情况下实现这一目标?

标签: javascriptarraystypescriptdictionary

解决方案


推荐阅读