简体   繁体   English

打字稿返回类型推断

[英]Typescript return type inference

In the following code snippet, typescript is able to infer the return type correctly: 在以下代码片段中,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'
}

How can I achieve this with following construct? 如何通过以下构造实现此目的?


{
  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? 
}

Here a more complex example (as requested): 这是一个更复杂的例子(根据要求):


  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 :)

The toolbox is not typed, toolbox2 is. 工具箱未输入,toolbox2是。 I want to bind the state to the specific functions. 我想将状态绑定到特定的函数。 In the end i wan't the user to write something like const toolbox = bindFactory(state, factory) . 最后,我不想让用户编写像const toolbox = bindFactory(state, factory)

Sorry, but this is the best complex example I came up with 对不起,这是我提出的最好的复杂例子

Ok, i figured a way - and it is actually very simple. 好吧,我想办法 - 实际上非常简单。 All you have to provide are the type definitions of the input parameters and let the compiler figure out the rest. 您需要提供的只是输入参数的类型定义,让编译器弄清楚其余部分。

So instead of 而不是

  type FAC_FUNCTION<S> = (state: S) => any

  const factory: FAC_FUNCTION<STATE> = state => (
    {
      hello() { 
        return 'Hello ' + state.value;
      }
    })

  const toolbox = factory(myState)

use: 采用:

  const factory = (state:PROPS) => (
    {
      hello() { 
        return 'Hello ' + state.value;
      }
    })

  const toolbox = factory(myState)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM