简体   繁体   English

TypeScript类型推断 - 函数的通用对象

[英]TypeScript Type Inference - Generic Object Of Functions

I was trying to implement a generic function that accepts an interface of functions and data, and passes the results from one another. 我试图实现一个接受函数和数据接口的通用函数,并将结果相互传递。

Inference is broken, any help will be appreciated. 推断被打破,任何帮助将不胜感激。

Link to a CodeSandbox of the Code That Does Not Compile 链接到不编译的代码的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
    };
  }
});

I believe this is not possible in the current Typescript version. 我相信在当前的Typescript版本中这是不可能的。

I've been experimenting with your code and it seems Type Inference work with some internal priority, which dictates that type should be inferred from parameter when possible, over inference from return value . 我一直在试验你的代码,似乎Type Inference有一些内部优先级,它规定应该在可能的情况下从参数推断出类型,而不是从返回值推断

If you'll remove the methods parameter from your code, you'll see computed return value - C , will be inferred correctly as: 如果您将从代码中删除methods参数,您将看到computed返回值 - C ,将被正确推断为:

{ computedMessage: string }

When methods included, C is inferred as unknown , since it is exist as a parameter in methods , so typescript will prefer to try to get the correct type based on methods behavior rather then computed . 当包含methodsC被推断为unknown ,因为它作为methods的参数存在,因此typescript将倾向于尝试基于methods行为获取正确的类型而不是computed

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

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