TypeScript typeof 函数返回值

标签 typescript

承认我有这样的功能

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/

相关文章:

javascript - 如何将 typescript 类型添加到 ES6 箭头函数?

Typescript 为 Observable 强制转换为 void

reactjs - 如何使用 Typescript 将组件传递到 react 路由器路由中?

angular - 在 Angular *ngFor 中打印对象项

angular - 在 FCMPlugin Ionic 2 中调用时 AlertController 不工作

angular - 如何在 Angular 中引用和使用另一个模块中的组件?

html - 在知道组件字符串名称的 Angular 2 中动态插入组件

Angular 6 : downloading file issue

typescript - 使用 const 的泛型作为接口(interface)

javascript - 将数组缓冲区转换为字符串