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

时间:2019-08-01 09:41:06

标签: javascript typescript type-inference typescript-generics

我试图实现一个通用函数,该函数接受函数和数据的接口,并将结果彼此传递。

推断被打破,任何帮助将不胜感激。

Link to a CodeSandbox of the Code That Does Not Compile

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
    };
  }
});

1 个答案:

答案 0 :(得分:3)

我相信这在当前的Typescript版本中是不可能的。

我一直在尝试使用您的代码,看来Type Inference具有某些内部优先级,该优先级指示在可能的情况下,应该根据参数而不是根据返回值进行推断,来推断类型

如果您将从代码中删除methods参数,则会看到computed返回值-C,将正确推断为:

{ computedMessage: string }

当包含methods时,C被推断为unknown,因为它作为参数存在于methods中,所以打字稿将倾向于尝试获取正确的类型。基于methods的行为,而不是computed