【问题标题】:Typescript return type inference打字稿返回类型推断
【发布时间】: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&lt;INPUT, OUTPUT&gt; = (input: INPUT) =&gt; OUTPUT 有什么问题?
  • 在示例中,输出是简单的值。在我的真实世界应用程序中,输出将是一个复杂的对象。此函数的用户不应该为编写该复杂对象的类型定义而烦恼。
  • 你能举个例子吗?通常您不需要指定整个复杂对象。以我的经验,这在现实世界中不是问题。
  • 等等,你的bindFactory()怎么了?这是我所期望的解决方案,它可以按照您想要的方式工作。

标签: typescript


【解决方案1】:

好的,我想出了一个办法——它实际上非常简单。您只需要提供输入参数的类型定义,剩下的就交给编译器了。

所以不是

  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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-09
    • 2020-04-02
    • 2020-12-20
    • 2016-08-03
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    相关资源
    最近更新 更多