My function has the capability to do either of the following:
- Process a string search term and return a
Promise
- Process a string search term along with a callback function, returning nothing (
void
)
Here is how the implementation looks like:
function fetcher(term: string): Promise<Result[]> {
return Promise.resolve([{id: 'foo'}, {id: 'bar'}])
}
type Callback = (results: Result[]) => void
function search<T>(term: string, cb?: T ): T extends Callback ? void : Promise<Result[]> {
const res = fetcher(term)
if(cb) {
res.then(data => cb(data)) // ❌ Type 'unknown' has no call signatures.(2349)
}
return res // ❌ Type 'Promise<Result[]>' is not assignable to type 'T extends Callback ? Promise<Result[]> : void'.
}
const promise = search('key') // ✅ Promise<Result[]>
const v = search('key', () => {}) // ✅ void
There are two key issues that need addressing in this code:
- The type of
cb
remains asunknown
even after being used within theif(cb)
statement return res
does not match the correct type, which should bePromise<Result[]>
What would be the proper way to define the types for such a function?