【问题标题】:How can I get the type from the result of a callback action?如何从回调操作的结果中获取类型?
【发布时间】:2021-10-28 19:14:40
【问题描述】:

我不太确定如何用使寻找解决方案变得非常困难的术语来表达我需要做的事情。我也尝试过阅读 Typescript 文档,但找不到与我想要的内容相关的任何内容。我有这个我正在尝试做的精简代码示例:

function test(
  name: string,
  actions: () => {/* I need something else here */}
) {
  return actions()
}

const foo = test('foo', () => ({
  bar() {
    console.log('foo.bar')
  }
}))

foo.bar() // Property 'bar' does not exist on type '{}'.ts(2339)

在这种情况下,是否可以让 Typescript 理解 bar() 应该在 foo 上可用?

【问题讨论】:

  • 只需将您的测试函数声明为。 function test(name: string, actions: () => T) { return actions(); }

标签: typescript typescript-types


【解决方案1】:

您可以使用typescript generics

function test<T>( //Generic type T
  name: string,
  actions: () => T // Callback return value
): T { // Whole functions return value
  return actions()
}

const foo = test('foo', () => ({
  bar() {
    console.log('foo.bar')
  }
}))

查看typescript playground

【讨论】:

    猜你喜欢
    • 2016-03-21
    • 1970-01-01
    • 2019-07-02
    • 2015-07-15
    • 2018-09-24
    • 2012-02-29
    • 1970-01-01
    • 2019-11-10
    • 2014-08-09
    相关资源
    最近更新 更多