【发布时间】:2019-04-17 08:03:24
【问题描述】:
在以下代码 sn-p 中,typescript 能够正确推断返回类型:
{
type IOFunction< OUTPUT> = (input: number) => OUTPUT
function createIOFunction<OUTPUT>(input: number, converter: IOFunction<OUTPUT>): OUTPUT {
return converter(input)
}
const x = createIOFunction(12, num => num + '!')
// x is of type 'string'. Typescript was able to infer the OUTPUT type correctly AND without me specifying what the output type should be
const y = createIOFunction(24, num => num * 2)
// y is of type 'number'
}
我怎样才能通过以下构造实现这一点?
{
type IOFunction<INPUT> = (input: INPUT) => any /* <-- What goes here ?? */
// I don't want the type to be IOFunction<INPUT, OUTPUT> = (input: INPUT) => OUTPUT
const convert: IOFunction<number> = num => num + '!'
const x = convert(12)
// x is of type any, not string
// how can x be inferred?
}
这里有一个更复杂的例子(根据要求):
interface STATE {
value: number
}
const myState: STATE = {
value: 12
}
type FAC_FUNCTION<S> = (state: S) => any
const factory: FAC_FUNCTION<STATE> = state => (
{
hello() {
return 'Hello ' + state.value;
}
})
const toolbox = factory(myState)
// toolbox.hello() <!--- not typed :(
type FACTORY_FUNCTION<S, OUTPUT> = (state:S) => OUTPUT
function bindFactory<S, OUTPUT>(state:S, fac: FACTORY_FUNCTION<S, OUTPUT>) {
return fac(state)
}
const toolbox2 = bindFactory(myState, state => ({
hello() {
return 'Hello ' + state.value
}
}))
toolbox2.hello() // typed :)
工具箱没有输入,toolbox2 是。我想将状态绑定到特定功能。最后我不想让用户写const toolbox = bindFactory(state, factory)之类的东西。
抱歉,这是我想出的最复杂的例子
【问题讨论】:
-
IOFunction<INPUT, OUTPUT> = (input: INPUT) => OUTPUT有什么问题? -
在示例中,输出是简单的值。在我的真实世界应用程序中,输出将是一个复杂的对象。此函数的用户不应该为编写该复杂对象的类型定义而烦恼。
-
你能举个例子吗?通常您不需要指定整个复杂对象。以我的经验,这在现实世界中不是问题。
-
等等,你的
bindFactory()怎么了?这是我所期望的解决方案,它可以按照您想要的方式工作。
标签: typescript