I have a function that calls api and returns a data of for example array of strings.
async function getData(){
const response = await fetchData()
return response
}
so the function signature is fixed to getData: () => string[]
now I need to be able to pass some processor function that would transform the response.
Like
async function getData<T>(process?: (data: Awaited<ReturnType<typeof fetchData>>) => T){
const response = await fetchData()
return process ? process(response) : response
}
but I get unknown type when this function is called
const result = await getData()
^
unknown type
The desired result is to get as type string[]
when process is not passed and return the T
when process
is there
also would be awesome to make T
optional
2
Answers
You can use conditional types:
Here’s playground
You can use a function overload signature to infer the correct return type for your case:
TS Playground
Be sure to check the documentation for the compiler option
exactOptionalPropertyTypes
, which enables stricter handling of optional types.