[英]TypeScript - Array reduce return object with specific type/interface
I'm creating a generic function that gets properties from an object using array.reduce.我正在创建一个通用函数,它使用 array.reduce 从对象中获取属性。 I would like the return type to only return the type of properties extracted from the original object
我希望返回类型只返回从原始对象中提取的属性类型
type Sample = {
name: string;
age: number;
isAlive: boolean;
}
const sample: Sample = {
name: "John Doe",
age: 22,
isAlive: true,
};
// What changes should I do here?
function getProps(...keys: (keyof Sample)[]) {
return keys.reduce((acc, key) => {
acc[key] = sample[key];
return acc;
}, {})
}
const result = getProps("name", "age");
/*
I would like the result to have a type of:
{
name: string;
age: number;
}
*/
I saw this being done in zustand.js but I don't know how they did it.我看到这是在 zustand.js 中完成的,但我不知道他们是如何做到的。 Any help is appreciated.
任何帮助表示赞赏。
Here's a quick solution.这是一个快速的解决方案。 The key is using generics and the
Pick
utility type:关键是使用泛型和
Pick
实用程序类型:
type Sample = {
name: string;
age: number;
isAlive: boolean;
}
const sample: Sample = {
name: "John Doe",
age: 22,
isAlive: true,
};
function getProps<K extends keyof Sample>(...keys: K[]): Pick<Sample, K> {
return keys.reduce((acc, key) => {
acc[key] = sample[key];
return acc;
}, {} as Pick<Sample, K>)
}
const result = getProps("name", "age");
// result has only name and age
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.