Typing Promise returning function with Result #430
-
Hi! I'm looking for help with how best to type a function like this: const getArtist
= (identifier) => fetchArtist (`/artists/${identifier}`)
.then ((response: GetArtistResponse) => Result.ok (response.data))
.catch (() => Result.err (ErrorMessage.ArtistNotFound)) I'd like to do something compact like this but TypeScript doesn't like it: const getArtist
: (_:string) => Promise<Result<Artist, ErrorMessage>>
= (identifier) => fetchArtist (`/artists/${identifier}`)
.then ((response: GetArtistResponse) => Result.ok (response.data))
.catch (() => Result.err (ErrorMessage.ArtistNotFound)) TypeScript is happy with this though: const getArtist
: (_:string) => Promise<Ok<Artist> | Err<ErrorMessage>>
= (identifier) => fetchArtist (`/artists/${identifier}`)
.then ((response: GetArtistResponse) => Result.ok (response.data))
.catch (() => Result.err (ErrorMessage.ArtistNotFound)) Is this just the way it has to be? Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Hi @kee-oth, thanks for the ask. You will need to provide the type for the initial parameter somehow—this isn’t a True Myth limitation but a TypeScript limitation. Unlike languages like F♯, OCaml, Elm, Haskell, etc., TypeScript does not do Hindley-Milner inference or any other kind of full program inference; any function parameter which is not explicitly typed in some way is implicitly typed as A couple other notes:
Net, I would write this like this: const getArtist = (identifier: string): Promise<Result<Artist, ErrorMessage>> =>
fetchArtist(`/artists/${identifier}`)
.then((response) => Result.ok(response.data))
.catch(() => Result.err(ErrorMessage.ArtistNotFound)) |
Beta Was this translation helpful? Give feedback.
Hi @kee-oth, thanks for the ask. You will need to provide the type for the initial parameter somehow—this isn’t a True Myth limitation but a TypeScript limitation. Unlike languages like F♯, OCaml, Elm, Haskell, etc., TypeScript does not do Hindley-Milner inference or any other kind of full program inference; any function parameter which is not explicitly typed in some way is implicitly typed as
any
. (I say “in some way” because callbacks can get their types from the context where they’re used, but the definition of the site they are passed to has to be typed well for that to work.) The best thing you can do is something like your final version or simply providing the type explicitly inline.