Skip to content

Instantly share code, notes, and snippets.

@tompng
Created June 19, 2020 09:42
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 tompng/518e8e6c1c3b288fc2a87322e4994381 to your computer and use it in GitHub Desktop.
Save tompng/518e8e6c1c3b288fc2a87322e4994381 to your computer and use it in GitHub Desktop.
export const fooPath = 'aa/:id/:foo/:bar'
type AllMethodPathAndParams = {
[fooPath]: {
GET: { id: number }
POST: undefined
}
}
function f<M extends 'GET' | 'POST', K extends keyof AllMethodPathAndParams>(
method: M,
path: K,
params: Exclude<AllMethodPathAndParams[K][M], undefined>
) {
console.log(method, path, params)
}
f('GET', fooPath, { id: 2 })
type PathSpec = string | { path: any; spec: any }
type ApiInfoBase = {
pathSpec: PathSpec[]
}
type Verbs = 'GET' | 'POST' | 'DELETE'
type ApiInfo = {
pathSpec: PathSpec[]
_paramType?: { [key in Verbs]?: any }
}
export const fooPath = {
pathSpec: ['/a', '/b', 'etc']
} as ApiInfoBase & { _paramType?: { GET: { id: number } } }
export const barPath = {
verb: 'GET' as const,
pathSpec: ['/a', 'etc']
} as ApiInfoBase & { _paramType?: { GET: { id: number }; POST: { foo: string } } }
function f<V extends Verbs, T extends ApiInfo>(
method: V,
info: T,
params: Exclude<Exclude<T['_paramType'], undefined>[V], undefined>
) {
console.log(method, info, params)
}
f('POST', barPath, { foo: 'a' })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment