declare function with overrides with one required and multiple inferred generics

33 Views Asked by At

Trying to do something like this:

declare function pipe<S, T1>(op1: OperatorFn<S, T1>): T1
declare function pipe<S, T1, T2>(op1: OperatorFn<S, T1>, op2: OperatorFn<T1, T2>): T2
declare function pipe<S, T1, T2, T3>(op1: OperatorFn<S, T1>, op2: OperatorFn<T1, T2>, op3: OperatorFn<T2,T3>): T3

I want S to be required, but I want to the rest to be inferred - whatever op1 returns is T1, whatever op2 returns is T2, if you know what I mean.

I know what I have above doesn't work, not at all sure how to make it work in my definition file, though.

EDIT: I know I can write something like this:

export interface pipe<S> {
    <T1>(op1: OperatorFn<S, T1>): S;
    <T1,T2>(op1: OperatorFn<S, T1>, op2: OperatorFn<T1,T2>): S;
}

But I need to declare a function in my interface file that then adheres to that interface. Not sure how to do that either.

EDIT #2:

The below seems to solve my problem easily enough:

type pipe<S> = <T1,T2>(op1: OperatorFn<S,T1>, op2?: OperatorFn<T1,T2>) => S

But then I don't know how to declare a function that adheres to that type in my definition file.

1

There are 1 best solutions below

0
On

Because T1 is not used anywhere else than inside the function, it allows you to do this.

This can easily extended with type T2 = typeof op2 and so on.

function pipe<S>(op1: OperatorFn<unkown, unknown>): S {
   type T1 = typeof op1 extends TEST<S, infer U> ? U : never
}

You also have to extend type S to match OperatorFn.