Recently, I have encountered some complex function types that need to be implemented. That is, the types of subsequent parameters are determined according to the types of the arguments of the preceding function.

We zhuanlan.zhihu.com/p/95828198 example, for example

interface FooParams {
  type: "foo"
  value: string
}

interface BarParams {
  type: "bar"
  value: number
}

type Params = FooParams | BarParams

function test<TParams extends Params> (
  type: TParams["type"],
  value: TParams["value"]
) :void {}
Copy the code

The purpose here is that the type of the second parameter value is determined by the type of the argument to the first parameter, which is actually the Dependent type. @Vilicvane introduces an implementation of multiple generic parameter constraints. Typescript does not currently support Dependent_type directly, but with support for function overloading and conditional type, We can implement a beggar version of the playground – Dependent_type_ Depdentype

The core idea of this example is:

  • Type Variable is split and mapped into unions of different function types by distributive Conditional Types and infer
  • Converts the function union to the function intersection with union2Intersection
  • The inerSection function can be overloaded as a function
  • When a function is overloaded, it exposes only the overload signature but not the implementation signature