我试图实现一个通用函数,它接受函数和数据的接口(interface),并相互传递结果。
推论被打破,任何帮助将不胜感激。
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
};
}
});
最佳答案
我相信这在当前的 Typescript 版本中是不可能的。
我一直在试验你的代码,看起来 Type Inference使用一些内部优先级,它规定类型应该尽可能从参数推断,而不是从返回值推断。
如果您从代码中删除 methods
参数,您将看到 computed
返回值 - C
,将被正确推断作为:
{ computedMessage: string }
当包含 methods
时,C
被推断为 unknown
,因为它作为参数存在于 methods
中,因此 typescript 将更愿意尝试根据方法
行为而不是计算
来获取正确的类型。
关于javascript - TypeScript 类型推断 - 函数的通用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57306146/