承认我有这样的功能
const createPerson = () => ({ firstName: 'John', lastName: 'Doe' })
如何在声明 createPerson
之前不声明接口(interface)或类型,获取返回值类型?
像这样:
type Person = typeof createPerson()
示例场景
我有一个 Redux 容器,可以将状态和分派(dispatch)操作映射到组件的 props。
容器/Counter.tsx
import { CounterState } from 'reducers/counter'
// ... Here I also defined MappedState and mapStateToProps
// The interface I would like to remove
interface MappedDispatch {
increment: () => any
}
// And get the return value type of this function
const mapDispatchToProps =
(dispatch: Dispatch<State>): MappedDispatch => ({
increment: () => dispatch(increment)
})
// To export it here instead of MappedDispatch
export type MappedProps = MappedState & MappedDispatch
export default connect(mapStateToProps, mapDispatchToProps)(Counter)
组件/Counter.tsx
import { MappedProps } from 'containers/Counter'
export default (props: MappedProps) => (
<div>
<h1>Counter</h1>
<p>{props.value}</p>
<button onClick={props.increment}>+</button>
</div>
)
我希望能够导出 mapDispatchToProps
的类型,而不必创建 MappedDispatch
接口(interface)。
我在这里减少了代码,但它让我输入了两次相同的内容。
最佳答案
原帖
typescript <2.8
我创建了一个允许解决方法的小库,直到将完全声明的方式添加到 TypeScript:
https://npmjs.com/package/returnof
还在 Github 上创建了一个问题,要求通用类型推断,这将允许一个完全声明的方式来做到这一点:
https://github.com/Microsoft/TypeScript/issues/14400
2018 年 2 月更新
typescript 2.8
TypeScript 2.8 引入了一个新的静态类型 ReturnType
,它允许实现这一点:
https://github.com/Microsoft/TypeScript/pull/21496
您现在可以以完全声明的方式轻松获取函数的返回类型:
const createPerson = () => ({
firstName: 'John',
lastName: 'Doe'
})
type Person = ReturnType<typeof createPerson>
关于TypeScript typeof 函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40590034/