簡體   English   中英

TypeScript類型推斷 - 函數的通用對象

[英]TypeScript Type Inference - Generic Object Of Functions

我試圖實現一個接受函數和數據接口的通用函數,並將結果相互傳遞。

推斷被打破,任何幫助將不勝感激。

鏈接到不編譯的代碼的CodeSandbox

function InitViewModel<S, C, M>(params: {
  state: S;
  computed: (s: S) => C;
  methods: (s: S, c: C) => M;
}) {
  const state = params.state;
  const computed = params.computed(state);
  const methods = params.methods(state, computed);
  return {
    state,
    computed,
    methods
  };
}

export const VM = InitViewModel({
  state: { message: "This Will Be Infered As expected" },
  computed: (state /* infered */) => ({
    computedMessage: state.message + " But This Will Not"
  }),
  methods: (state /* infered */, computed /*  inferred wrong */) => {
    return {
      logName: () => console.log(state.message),
      logComputedName: () => console.log(computed.computedMessage) // Does not compile
    };
  }
});

我相信在當前的Typescript版本中這是不可能的。

我一直在試驗你的代碼,似乎Type Inference有一些內部優先級,它規定應該在可能的情況下從參數推斷出類型,而不是從返回值推斷

如果您將從代碼中刪除methods參數,您將看到computed返回值 - C ,將被正確推斷為:

{ computedMessage: string }

當包含methodsC被推斷為unknown ,因為它作為methods的參數存在,因此typescript將傾向於嘗試基於methods行為獲取正確的類型而不是computed

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM