Tipar código async en TypeScript
Tipos Promise, resultados con await y el tipado de un wrapper de fetch.
interface ApiError {
status: number;
message: string;
}
type ApiResult<T> = { data: T } | { error: ApiError };
async function getJSON<T>(url: string,
parse: (raw: unknown) => T): Promise<ApiResult<T>> {
const response = await fetch(url);
if (!response.ok) {
return { error: { status: response.status, message: response.statusText } };
}
try {
return { data: parse(await response.json()) };
} catch (cause) {
return { error: { status: 0, message: String(cause) } };
}
}
interface Tour {
slug: string;
steps: number;
}
const parseTour = (raw: unknown): Tour => {
const value = raw as Tour;
if (typeof value?.slug !== "string") throw new TypeError("bad tour");
return value;
};
type Loaded = Awaited<ReturnType<typeof getJSON<Tour>>>;
console.log(typeof getJSON, typeof parseTour, {} as Loaded);
Cómo funciona
- El tipo de retorno de una función async siempre es una Promise.
- Un parámetro genérico lleva la forma de la respuesta a través de todo.
- El
unknowndel JSON debe estrecharse antes de usarse.
Palabras clave y builtins usados aquí
ApiErrorPromiseStringTasasyncawaitcatchconstfunctionifinterfacenumberparsereturnstringthrowtrytypeunknown
El intento, en números
- Líneas
- 33
- Caracteres a escribir
- 797
- Tokens
- 217
- Ritmo de tres estrellas
- 105 tpm
Al ritmo de tres estrellas de 105 tokens por minuto, este intento toma unos 124 segundos.
Paso 2 de 2 en Tipos async; paso 2 de 8 en Async y módulos.