[英]Dynamic return type of object properties using TypeScript
我有一個函數,它接收一個對象並返回一個具有相同屬性名稱的方法對象:
function someGenerator<P extends {}>(params: P) {
return Object.keys(params).reduce((acc, key) => ({
...acc,
[key]: () => {
console.log(params[key]);
},
}), {});
}
基本上我想像這樣使用它:
type Params = {
str: string;
}
const params = {
str: 'some text',
}
const someInstance = someGenerator<Params>(params);
someInstance.str();
我試圖定義該函數的返回類型:
type ReturnType<P> = {
[K in keyof P]: () => void;
}
但是這種類型並沒有像我預期的那樣工作,因為返回類型的定義沒有像它應該的那樣保存參數。
任何人都可以幫助定義返回類型嗎?
.reduce
推斷類型通常被定義為累加器的起始值。 當我有一個返回reduce
d 值的函數時,我通常會這樣做:
function someGenerator<P extends Record<string, any>>(params: P) {
return Object.keys(params).reduce(
(acc, key) => ({
...acc,
[key]: () => {
console.log(params[key]);
}
}),
{} as Record<keyof P, () => void>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.