Skip to content

Instantly share code, notes, and snippets.

@pmn4
pmn4 / typed-api-request.d.ts
Created September 20, 2023 19:31
Why is the NextApiResponse type generic, but `NextApiRequest` is not?
// Add type safety to NextApiRequest
type TypedNextApiRequest<Q, B> = Omit<NextApiRequest, 'body' | 'query'> & {
// make req.query have the keys we expect, but AsQuery will turn the values
// into strings or string arrays. Partial is there because you never know
// whether the request will be well-formed
query: Partial<AsQuery<Q>>;
// make req.body have the keys and value types we expect, however, know that
// the data will be deserialized from JSON, so, for example, Dates will be
// strings. again Partial is there to enforce defensive code
body: Partial<Deserialized<B>>;
@pmn4
pmn4 / promise-predicates.ts
Created November 3, 2023 14:38
Predicates for Cleanly Handling Settled Promises
// Filtering
export function isFulfilled<T>(
value: PromiseSettledResult<T>,
_index?: number,
_array?: PromiseSettledResult<T>[],
): value is PromiseFulfilledResult<T> {
return value.status === 'fulfilled';
}