Typescript:如何根据参数类型获取函数的返回类型?

阿特姆·博卡卡列夫(Artem Bochkarev)

我希望返回类型基于“ 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"

可能吗 ?

贾卡尔兹

编译器不够聪明,无法自行解决这个问题,但是您可以肯定地描述您想要的类型,并在实现中使用类型断言exampleFn()来防止其抱怨...请记住,此类断言会转移从编译器到您的类型安全负担。

这是我认为您想要的类型:

{ [K in Extract<keyof T, keyof Interface>]: typeof DEFAULT_VALUES[K] }

基本上,您正在创建映射类型,其中键是T也存在于其中的键Interface(可能T包含更多键,因为T extends Partial<Interface>允许这种扩展;如果您确实想禁止这样做,则可以,但是现在我要使其保持原样),并且值是该值中对应的类型DEFAULT_VALUES

这是实现:

const exampleFn = <T extends Partial<Interface>>(config: T) => {
   const map = {} as any;

   Object.entries(config).forEach(([key, val]) => {
      map[key] = DEFAULT_VALUES[key as keyof Interface];
   });

   return map as { [K in Extract<keyof T, keyof Interface>]: typeof DEFAULT_VALUES[K] };
};

您可以看到我在断言这keykeyof Interface(因为key只有string编译器才知道它),并且这map是所需的返回类型。让我们看看它是如何工作的:

const example1 = exampleFn({ a: 123 });
console.log(example1.a(123)); // 124
console.log(example1.b); // undefined
// error!  --------> ~
// Property 'b' does not exist on type '{ a: (num: number) => number; }'
const example2 = exampleFn({ b: 'asd' });
console.log(example2.b("asd")); // aasd
const example3 = exampleFn({ a: 123, b: 'asd' });
console.log(example3.b("asd")); // aasd
console.log(example3.a(123)); // 124

在我看来很好。

操场上的代码链接

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

TypeScript:如何根据函数参数类型设置函数返回值类型

如何获取Scala函数的参数/返回类型?

如何从Typescript中的函数获取参数类型

如何根据参数类型转换函数的返回类型?

TypeScript根据类型参数返回不同的类型

根据TypeScript中的参数在字典中定义函数的返回类型

Typescript 根据参数强制函数返回类型为接口的键

TypeScript - 基于参数类型的函数返回类型

TypeScript:如何让返回类型成为参数的类型?

根据参数定义函数的返回类型

如何使TypeScript基于返回值识别函数的参数类型?

如何获取函数参数类型?

TypeScript 类型获取约束函数类型泛型的返回类型

Typescript从参数返回函数的类型

基于输入参数的TypeScript函数返回类型

从枚举参数推断Typescript函数返回类型

根据参数返回类型

如何根据函数的type参数的type参数编写具有多态返回类型的函数?

Typescript函数的返回类型取决于参数的数量或类型

TypeScript映射函数从其参数类型返回的类型

TypeScript返回参数的类型

如何根据函数返回的对象指定类型

有没有办法让 TypeScript 根据调用参数推断函数返回值的类型?

Typescript - 获取嵌入在函数类型参数中的类型

Typescript:获取函数类型的最后一个参数的类型

如何根据类方法的返回类型声明参数类型?

如何根据Typescript中的字符串参数定义函数的参数类型?

如何根据“类似函数”的参数推断函数模板的返回类型?

如何使函数接受字符串参数,并根据该函数返回不同的结构类型?