承认我有这样的功能
const createPerson = () => ({ firstName: 'John', lastName: 'Doe' })
Run Code Online (Sandbox Code Playgroud)
如果在声明之前没有声明接口或类型,我怎么能createPerson得到返回值类型?
像这样的东西:
type Person = typeof createPerson()
Run Code Online (Sandbox Code Playgroud)
我有一个Redux容器,它将状态和调度操作映射到组件的props.
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)
Run Code Online (Sandbox Code Playgroud)
import { MappedProps } from 'containers/Counter'
export default (props: MappedProps) => (
<div>
<h1>Counter</h1>
<p>{props.value}</p>
<button onClick={props.increment}>+</button>
</div>
)
Run Code Online (Sandbox Code Playgroud)
我希望能够导出类型而mapDispatchToProps无需创建MappedDispatch接口.
我在这里减少了代码,但它让我输入两次相同的东西.
kub*_*ube 48
我创建了一个允许解决方法的小库,直到将一个完全声明的方式添加到TypeScript:
https://npmjs.com/package/returnof
还在Github上创建了一个问题,要求进行通用类型推断,这将允许完全声明性的方式来执行此操作:
https://github.com/Microsoft/TypeScript/issues/14400
TypeScript 2.8引入了一种新的静态类型ReturnType,允许实现:
https://github.com/Microsoft/TypeScript/pull/21496
您现在可以以完全声明的方式轻松获取函数的返回类型:
const createPerson = () => ({
firstName: 'John',
lastName: 'Doe'
})
type Person = ReturnType<typeof createPerson>
Run Code Online (Sandbox Code Playgroud)
0x6*_*015 13
这https://github.com/Microsoft/TypeScript/issues/4233#issuecomment-139978012可能会有所帮助:
let r = true ? undefined : someFunction();
type ReturnType = typeof r;
Run Code Online (Sandbox Code Playgroud)
改编自https://github.com/Microsoft/TypeScript/issues/14400#issuecomment-291261491
const fakeReturn = <T>(fn: () => T) => ({} as T)
const hello = () => 'World'
const helloReturn = fakeReturn(hello) // {}
type Hello = typeof helloReturn // string
Run Code Online (Sandbox Code Playgroud)
链接中的示例使用null as T而不是{} as T,但打破了Type 'null' cannot be converted to type 'T'.
最好的部分是fakeReturn实际上没有调用作为参数给出的函数.
使用TypeScript 2.5.3进行测试
TypeScript 2.8引入了一些预定义的条件类型,包括ReturnType<T>获取函数类型的返回类型.
const hello = () => 'World'
type Hello = ReturnType<typeof hello> // string
Run Code Online (Sandbox Code Playgroud)