如何从回调操作的结果中获取类型?

How can I get the type from the result of a callback action?

我不太确定如何用术语来表达我需要做的事情,这使得寻找解决方案变得非常困难。我也尝试阅读 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 上可用?

您可以使用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

中查看