【发布时间】:2021-01-11 06:09:06
【问题描述】:
我希望返回类型基于“config”参数
现在 exampleFn 函数的返回类型为空 {}
interface Interface {
a: number;
b: string;
}
const DEFAULT_VALUES = {
a: (num: number) => 1 + num,
b: (str: string) => 'a' + str,
}
const exampleFn = <T extends Partial<Interface>>(config: T) => {
const map = {};
Object.entries(config).forEach(([key, val]) => {
map[key] = DEFAULT_VALUES[key];
});
return map;
};
const example1 = exampleFn({ a: 123 }); // I want example1 return type to be "{a: (num: number) => number}"
const example2 = exampleFn({ b: 'asd' }); // I want example2 return type to be "{b: (str: string) => string}"
const example3 = exampleFn({ a: 123, b: 'asd' }); // I want example3 return type to be "{a: (num: number) => number, b: (str: string)} => string"
有可能吗?
【问题讨论】:
标签: typescript typescript-typings typescript-generics