简体   繁体   English

打字稿推断执行具有相同参数签名的可选函数参数的高阶函数的类型

[英]Typescript infer type of higher-order function that executes optional function parameters with same argument signatures

Let's say I have a function that takes two functions f and g as arguments and returns a function that executes f and g and returns an object with the results.假设我有一个函数,它接受两个函数fg作为参数,并返回一个执行fg并返回带有结果的对象的函数。 I also want to enforce that f and g have the same signature.我还想强制fg具有相同的签名。 This is easy enough with conditional types:对于条件类型,这很容易:

type ArgumentTypes<F extends Function> = F extends (...args: infer A) => any ? A : never;
function functionPair<
    F extends (...args: any[]) => any,
    G extends (...args: ArgumentTypes<F>) => any
>
(f: F, g: G): (...args: ArgumentTypes<F>) => { f: ReturnType<F>, g: ReturnType<G> }
{
    return (...args: ArgumentTypes<F>) => ({ f: f(...args), g: g(...args) });
}

functionPair((foo: string) => foo, (bar: number) => bar); // Error, incompatible signatures, as expected
functionPair((foo: string) => foo, (bar: string) => bar.length); // (foo: string) => { f: string; g: number; }, as expected

Now, what if I want to make f and g optional , and have the shape of the returned object change as a result?现在,如果我想让fg可选项,并因此改变返回对象的形状怎么办? That is, if f or g is undefined , their key should be missing from the resulting object:也就是说,如果fgundefined ,则结果对象中应该缺少它们的键:

functionPair(); // Should be () => {}
functionPair(undefined, undefined); // Should be () => {}
functionPair((foo: string) => foo); // Should be (foo: string) => { f: string }
functionPair(undefined, (bar: string) => foo.length); // Should be (bar: string) => { g: number }
functionPair((foo: string) => foo, (bar: string) => foo.length); // Should be (foo: string) => { f: string, g: number }, as before

I've been trying to accomplish this with conditional types, but I'm having some trouble with conditionally enforcing the shape of the resulting function.我一直在尝试使用条件类型来实现这一点,但是在有条件地强制执行结果函数的形状时遇到了一些麻烦。 Here's what I have so far (strict null checks are off):到目前为止,这是我所拥有的(关闭了严格的空检查):

function functionPair<
    A extends F extends undefined ? G extends undefined ? [] : ArgumentTypes<G> : ArgumentTypes<F>,
    F extends (...args: any[]) => any = undefined,
    G extends F extends undefined ? (...args: any[]) => any : (...args: ArgumentTypes<F>) => any = undefined
>
(f?: F, g?: G): (...args: A) =>
    F extends undefined
    ? G extends undefined ? {} : { g: ReturnType<G> }
    : G extends undefined ? { f: ReturnType<F> } : { f: ReturnType<F>, g: ReturnType<G> }
{ /* implementation... */ }

const a = functionPair(); // () => {}, as expected
const b = functionPair((foo: string) => foo); // (foo: string) => { f: string; }, as expected
const c = functionPair((foo: string) => foo, (bar: number) => bar); // Error, incompatible signatures, as expected
const d = functionPair((foo: string) => foo, (bar: string) => bar.length); // (foo: string) => { f: string; g: number; }, as expected

const e = functionPair(undefined, undefined); // INCORRECT! Expected () => {}, got (...args: unknown[] | []) => {} | { f: any; } | { g: any; } | { f: any; g: any; }
const f = functionPair(undefined, (bar: string) => bar.length); // INCORRECT! Expected (bar: string) => { g: number; } but got (...args: unknown[] | [string]) => { g: number; } | { f: any; g: number; }

By the way, I know that this is technically possible with overloads, as below, but I'd really like to understand how to do it without them.顺便说一句,我知道这在技术上可以通过重载实现,如下所示,但我真的很想了解如何在没有它们的情况下做到这一点。

function functionPairOverloaded(): () => {}
function functionPairOverloaded(f: undefined, g: undefined): () => {}
function functionPairOverloaded<F extends (...args: any[]) => any>(f: F): (...args: ArgumentTypes<F>) => { f: ReturnType<F> }
function functionPairOverloaded<G extends (...args: any[]) => any>(f: undefined, g: G): (...args: ArgumentTypes<G>) => { g: ReturnType<G> }
function functionPairOverloaded<F extends (...args: any[]) => any, G extends (...args: ArgumentTypes<F>) => any>(f: F, g: G): (...args: ArgumentTypes<F>) => { f: ReturnType<F>, g: ReturnType<G> }
function functionPairOverloaded<F extends (...args: any[]) => any, G extends (...args: any[]) => any>(f?: F, g?: G) { /* implementation... */ }

Assuming you have --strictNullChecks turned on, I guess I'd do it this way:假设您打开了--strictNullChecks ,我想我会这样做:

type Fun = (...args: any[]) => any;
type FunFrom<F, G> = F extends Fun ? F : G extends Fun ? G : () => {};
type IfFun<F, T> = F extends Fun ? T : never;
type Ret<T> = T extends (...args: any[]) => infer R ? R : never

declare function functionPair<
  F extends Fun | undefined = undefined,
  G extends ((...args: (F extends Fun ? Parameters<F> : any[])) => any) 
    | undefined = undefined
>(
  f?: F, 
  g?: G
): (...args: Parameters<FunFrom<F, G>>) => {
  [K in IfFun<F, 'f'> | IfFun<G, 'g'>]: K extends 'f' ? Ret<F> : Ret<G> 
};

That's fairly ugly, but it does give you the behavior you're looking for:这相当丑陋,但它确实为您提供了您正在寻找的行为:

const a = functionPair(); // () => {}, as expected
const b = functionPair((foo: string) => foo); // (foo: string) => { f: string; }, as expected
const c = functionPair((foo: string) => foo, (bar: number) => bar); // Error, incompatible signatures, as expected
const d = functionPair((foo: string) => foo, (bar: string) => bar.length); // (foo: string) => { f: string; g: number; }, as expected
const e = functionPair(undefined, undefined); // () => {}, as expected
const f = functionPair(undefined, (bar: string) => bar.length); // (bar: string) => { g: number; }, as expected

I decided to go with just two type parameters F and G and instead of A use Parameters<FunFrom<F, G>> .我决定只使用两个类型参数FG而不是A使用Parameters<FunFrom<F, G>> Note that Parameters is a built-in type function similar to your ArgumentTypes .请注意, Parameters是类似于您的ArgumentTypes的内置类型函数。

Also, for the return type of the returned function I do a somewhat ugly mapped type.另外,对于返回函数的返回类型,我做了一个有点难看的映射类型。 I first was planning to do something like IfFun<F, {f: Ret<F>}> & IfFun<G, {g: Ret<G>}> , which is (I believe) more understandable, but the resulting type {f: X, g: Y} is nicer than the intersection {f: X} & {g: Y} .我首先计划做一些类似IfFun<F, {f: Ret<F>}> & IfFun<G, {g: Ret<G>}> ,这(我相信)更容易理解,但结果类型{f: X, g: Y}比交集{f: X} & {g: Y}更好。

Anyway, hope that helps.无论如何,希望有帮助。 Good luck!祝你好运!


If you want to be able to turn --strictNullChecks off, then the definitions get even hairier:如果您希望能够关闭--strictNullChecks ,那么定义会变得更加复杂:

type Fun = (...args: any[]) => any;
type AsFun<F> = [F] extends [Fun] ? F : never
type FunFrom<F, G> = AsFun<IfFun<F, F, IfFun<G, G, () => {}>>>;
type IfFun<F, Y, N=never> = F extends undefined ? N : 
  0 extends (1 & F) ? N : F extends Fun ? Y : N;
type Ret<T> = T extends (...args: any[]) => infer R ? R : never

declare function functionPair<
  F extends Fun | undefined = undefined,
  G extends ((...args: IfFun<F, Parameters<F>, any[]>) => any)
  | undefined = undefined
  >(
    f?: F,
    g?: G
  ): (...args: Parameters<FunFrom<F, G>>) => {
    [K in IfFun<F, 'f'> | IfFun<G, 'g'>]: K extends 'f' ? Ret<F> : Ret<G>
  };

The difference is that IfFun<> needs to be able to distinguish functions from undefined and any , both of which pop up in unfortunate places when you turn off --strictNullChecks .不同之处在于IfFun<>需要能够区分函数与undefinedany ,当您关闭--strictNullChecks时,这两者都会在不幸的地方弹出。 That's because undefined extends Function ? true : false那是因为undefined extends Function ? true : false undefined extends Function ? true : false starts returning true , and any starts getting inferred when you pass the manual undefined value into the functions. undefined extends Function ? true : false开始返回true ,当您将手动undefined值传递给函数时, any开始都会被推断出来。 Distinguishing undefined is reasonably straightforward since Function extends undefined ? true : false区分undefined相当简单,因为Function extends undefined ? true : false Function extends undefined ? true : false is still false , but distinguishing any is annoying and involves some funny business . Function extends undefined ? true : false仍然是false ,但是区分any都很烦人,并且涉及一些有趣的事情

Good luck again!再次祝你好运!

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM