In the following code, I try to create a type-safe function that access the data property of the given input. My goal is to avoid repeating the access to data everywhere, and for this to be worth it I would like to keep boilerplate to a minimum (e.g. I would like TypeScript to infer as many type as possible).
interface User {
name: string
}
interface HttpResponse<T> {
data: T
status: number
}
type HttpPromise<T> = Promise<HttpResponse<T>>
function fetch<T>(url: string): HttpPromise<T> {
return
}
function getData<T>(response: HttpResponse<T>): T {
return response.data
}
// Doesn't work: 'Promise<{}>' is not assignable to type 'Promise<User>'.
function fetchUser(): Promise<User> {
return fetch('https://...').then(getData)
}
I know how to make it work by explicitly stating more types, but I don't know why this doesn't work already. In particular:
- Where does the
{}type come from (inPromise<{}>)? - Why can't TypeScript infer the type of the expression properly, based on the return type?