Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6290

A way to infer types based on the return value of the function in react prop

$
0
0

So i have this component definition that accepts two generics

function AsyncFlatList<ApiResponse, Item>({}: {  url: string;  transformResponse: (response: ApiResponse) => Item[];  keyExtractor: (item: Item) => string;}) {  // ignore the implementation  return <></>;}

I call the component like this

type Post = {    id: number    title: string    body: string    userId: number}type PostMapped = {   id: string   title: string   body: string}<AsyncFlatList<Post[], PostMapped>  url="https://jsonplaceholder.typicode.com/posts"  transformResponse={(response) => response}  // The type of post params below is coming from `PostMapped`  keyExtractor={(post) => post.id}/>

The problem is that I don't want to define PostMapped explicitly. I want it to be inferred from the type of the return value on the transformResponse prop.

So that i can use the component like this:

<AsyncFlatList<Post[]>  url="https://jsonplaceholder.typicode.com/posts"  transformResponse={(response) =>     response.map((singleResponse) => ({       id: singleResponse.id.toString(),       title: singleResponse.title,       body: singleResponse.body,     }))  } // post types below will be inferred based on what's return from transformResponse // that is why we can use post.id directly without types issue because it is already transformed to string // in the transformResponse prop above  keyExtractor={(post) => post.id}/>

and I don't have to define PostMapped anymore since it will be inferred.

Kindly help to achieve that. Thanks


Viewing all articles
Browse latest Browse all 6290

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>