[英]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;
}
expect预计
const params1 = test(json, ['a']); const params1 = test(json, ['a']); // params1 get key a from jsonData
// params1 从 jsonData 中获取 key a
const params2 = test(json, ['a', 'b']); const params2 = test(json, ['a', 'b']); // params2 get type key a、b from jsonData
// params2 从 jsonData 中获取类型键 a、b
But now the grammar is wrong, what should I do to make the program work correctly但是现在语法错误,应该怎么做才能让程序正常运行
A quick typing solution to make this work.一个快速打字解决方案,使这项工作。
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.