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



我真的不知道如何表达我需要做的事情,这使得寻找解决方案非常困难。我也试着阅读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泛型

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中查看

最新更新