【发布时间】:2019-02-19 16:30:42
【问题描述】:
承认我有这样的功能
const createPerson = () => ({ firstName: 'John', lastName: 'Doe' })
我如何在声明createPerson之前不声明接口或类型,获取返回值类型?
类似这样的:
type Person = typeof createPerson()
示例场景
我有一个 Redux 容器,它将状态和调度动作映射到组件的 props。
containers/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)
components/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接口。
我在这里减少了代码,但它让我输入了两次相同的东西。
【问题讨论】:
-
为什么?重点是什么?你能添加一个有意义的场景吗?
-
@NitzanTomer 我编辑了我的问题以添加一个具体的场景。
-
我认为你做不到。无法根据函数返回值的类型来定义类型。
标签: typescript