Created
June 19, 2020 09:42
-
-
Save tompng/518e8e6c1c3b288fc2a87322e4994381 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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