在以下代码片段中,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)
.
对不起,但这是我想出的最好的复杂例子
好的,我想出了一个方法 - 它实际上非常简单。您只需要提供输入参数的类型定义,然后让编译器找出其余部分。
所以代替
type FAC_FUNCTION<S> = (state: S) => any
const factory: FAC_FUNCTION<STATE> = state => (
{
hello() {
return 'Hello ' + state.value;
}
})
const toolbox = factory(myState)
用:
const factory = (state:PROPS) => (
{
hello() {
return 'Hello ' + state.value;
}
})
const toolbox = factory(myState)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句