Skip to content

Instantly share code, notes, and snippets.

@JavadocMD
Created August 24, 2019 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JavadocMD/91c04a8fbbc8625c85e63c0736fdab1a to your computer and use it in GitHub Desktop.
Save JavadocMD/91c04a8fbbc8625c85e63c0736fdab1a to your computer and use it in GitHub Desktop.
Express handler type constraints.
import { Request, NextFunction } from 'express'
interface JsonResponse<T> {
status(code: number): JsonResponse<T>
json(value: T): JsonResponse<T>
}
type JsonHandler<T> = (
req: Request,
res: JsonResponse<T>,
next: NextFunction
) => void
export const handleFoo: JsonHandler<Foo> = async (req, res, next) => {
const foo = await getFoo()
res.json(foo) // Error if `foo` is not of type Foo
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment