简体   繁体   English

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

[英]Typescript: How can I get return type of function based on argument type?

I want return type to be based on "config" argument我希望返回类型基于“config”参数

now return type of exampleFn function is empty {}现在返回 exampleFn function 的类型为空 {}

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"

is it possible?可能吗?

The compiler won't be smart enough to figure this out on its own, but you can certainly describe the type you want and use type assertions inside the implementation of exampleFn() to prevent it from complaining... keeping in mind that such type assertions shift the burden of type safety from the compiler to you.编译器不会聪明到自己解决这个问题,但你当然可以描述你想要的类型并在exampleFn()的实现中使用类型断言来防止它抱怨......记住这样的类型断言将类型安全的负担从编译器转移到您身上。

Here's the type I think you want:这是我认为你想要的类型:

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

Basically you are making a mapped type where the keys are the keys from T which are also present in Interface (it is possible for T to contain more keys because T extends Partial<Interface> allows such extension; if you really want to prohibit this you can, but for now I'm going to leave this as you have it), and the values are the corresponding types from the DEFAULT_VALUES value.基本上你正在制作一个映射类型,其中键是来自T的键,它们也存在于Interface中( T可能包含更多键,因为T extends Partial<Interface>允许这样的扩展;如果你真的想禁止这个,你可以,但是现在我将保留它),并且值是来自DEFAULT_VALUES值的相应类型。

Here's the implementation:这是实现:

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] };
};

You can see that I am asserting that key is keyof Interface (since key is only known to be string by the compiler) and that map is the desired return type.您可以看到我断言keykeyof Interface (因为编译器只知道keystring )并且map是所需的返回类型。 Let's see how it works:让我们看看它是如何工作的:

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

Looks good to me.在我看来很好。

Playground link to code Playground 代码链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据 Typescript 中的参数控制返回类型? - How can I control the return type based on an argument in Typescript? TypeScript:你能根据函数的参数定义一个返回类型结构吗? - TypeScript: Can you define a return Type structure based on an argument of the function? 在这种情况下,TypeScript 能否根据参数推断出 function 返回类型? - Can TypeScript infer a function return type based on an argument in this scenario? Typescript function 基于参数的返回类型 - Typescript function return type based on argument 我如何让 typescript 根据 function2E977777777777777777777777777777777777777777777777777777777777777777777777777777777777BED18 的返回类型 functionC17A94F14Z 的返回类型来推断 function 的返回类型 - How do I get typescript to infer the return type of a function based on the return type on a function of its arguments 如何让 TypeScript 根据返回值识别函数参数的类型? - How do I make TypeScript recognize the type of an argument to a function based on the return? TypeScript:如何根据 function 参数类型设置 function 返回值类型 - TypeScript: How to set function return value type based on function argument type TypeScript:根据返回类型推断参数类型 - TypeScript: Infer argument type based on return type 基于 Typescript 中的参数类型的条件返回类型 - Conditional return type based on argument type in Typescript 如何创建一个泛型 typescript 类型 function 并从参数类型推断出返回类型? - How do I make a generic typescript type function that has the return type inferred from the argument type?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM