Nabuska
Nabuska

Reputation: 463

Creating type from functions return value

I'm trying to get rid of repetition in my typescript react code and I was wondering if it was possible to create a type from functions known return type?

Something like:

const mapStateToProps = (state: StoreState) => ({settings: store.settings})
type Props = ReturnTypeOf<typeof mapStateToProps>

Upvotes: 1

Views: 48

Answers (1)

CRice
CRice

Reputation: 32276

TypeScript actually uses exactly this as an example for conditional types in the handbook:

type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;

For your example:

const mapStateToProps = (state: StoreState) => ({settings: store.settings})
type Props = ReturnType<typeof mapStateToProps>

Upvotes: 2

Related Questions