Reputation: 1
Suppose we have the following abstractions to retrieve data from API:
Class for storing data
class DataItem<T> {
data?: T | null
}
Function for query
function queryData (
fn: () => Promise<any>
item: DataItem<any>
transformResponse?: (value: any) => any // value - result from fn
)
We want to use this as follows:
const item = new DataItem<ItemDto>()
async function request (): Promise<ItemDto> { ... }
queryData(
() => request()
item
)
Is it possible to do the following without generic queryData
function:
fn
matches the type stored in item
?transformResponse
, can we check that its return value matches item
type?transformResponse
, can we check that its argument value
is the same as the type returned from the function fn
?Upvotes: 0
Views: 66
Reputation: 686
No. A generic type variable is exactly the tool that will allow you to do this. The following should meet your requirements:
function queryData<T>(
fn: () => Promise<T>,
item: DataItem<T>,
transformResponse: (value: Promise<T>) => DataItem<T>
)
Upvotes: 1