打字稿返回类型推断

时间:2019-04-17 08:03:25

标签: 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)的内容。

对不起,但这是我想出的最好的复杂示例

1 个答案:

答案 0 :(得分:0)

好的,我想出了一种方法-实际上很简单。您只需要提供输入参数的类型定义,然后让编译器找出其余的内容即可。

所以不是

  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)