深刻typescript: 簡易 dependent type 實現

最近常常碰到有同事須要一些實現的複雜的函數類型,即根據函數前序的函數的實參類型肯定後續參數的類型。typescript

咱們以 zhuanlan.zhihu.com/p/95828198 的例子爲例markdown

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 {}
複製代碼

這裏的目的是,第二個參數 value 的類型由第一個參數的實參類型肯定,這實際上就是 Dependent type , @vilicvane 介紹了一種經過多泛型參數約束的實現, _雖然 Typescript 目前不直接支持 Dependent_type,可是藉助於其函數重載和 conditional type 的支持,咱們能夠實現一個乞丐版 dependent_type_ depdentype playground函數

本例的核心思路就是:oop

  • 經過 distributive conditional types 和 infer 將 Type Variable 進行拆分映射爲不一樣的函數類型的 union
  • 經過 union2intersection 將 函數 union 轉換爲函數 intersection
  • 函數 inersection 能夠當作函數重載使用
  • 函數重載時只對外暴露 overload signature 並不對外暴露 implementation signature
相關文章
相關標籤/搜索