繁体   English   中英

如何从 typescript 中的数组中获取动态键值

[英]How do I get dynamic key values from an array in typescript

const jsonData = {
  a: '123',
  b: '456',
  c: '789'
}

type needArr = string[]


function test(obj: any, array: needArr): {
  [props: T in needArr]: string
} {
  const newObj = {};
  for (let item of array) {
    newObj[ item ] = obj[ item ] || '';
  }
  return newObj;
}

预计

const params1 = test(json, ['a']); // params1 从 jsonData 中获取 key a

const params2 = test(json, ['a', 'b']); // params2 从 jsonData 中获取类型键 a、b

但是现在语法错误,应该怎么做才能让程序正常运行

一个快速打字解决方案,使这项工作。

export type ValuesOf<T extends any[]>= Record<T[number], unknown>;
function test(obj: Record<string, unknown>, array: (keyof JSONDataType)[]): ValuesOf<typeof array> {
  const newObj = {} as Record<string, unknown>;
  for (let item of array) {
    newObj[ item ] = obj[ item ] || '';
  }
  return newObj;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM