[route-parser] Improve type-safety by making the Route class generic (#35216)

This commit is contained in:
Lorefnon
2019-05-14 04:42:34 +05:30
committed by Nathan Shively-Sanders
parent 88e22907b4
commit e63cb5725e
2 changed files with 17 additions and 3 deletions

View File

@@ -2,8 +2,9 @@
// Project: http://github.com/rcs/route-parser
// Definitions by: Ian Ker-Seymer <https://github.com/ianks>, Bob Buehler <https://github.com/bobbuehler>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
declare class Route {
declare class Route<TParams extends {} = { [i: string]: any }> {
/**
* Represents a route
* @example
@@ -23,7 +24,7 @@ declare class Route {
* var route = new Route('/:one/:two')
* route.match('/foo/bar/') // -> {one: 'foo', two: 'bar'}
*/
match(pathname: string): { [i: string]: string } | false;
match(pathname: string): {[k in keyof TParams]: string} | false;
/**
* Reverse a route specification to a path, returning false if it can't be
@@ -32,7 +33,7 @@ declare class Route {
* var route = new Route('/:one/:two')
* route.reverse({one: 'foo', two: 'bar'}) -> '/foo/bar'
*/
reverse(params: { [i: string]: any }): string | false;
reverse(params: TParams): string | false;
}
declare namespace Route {}

View File

@@ -1,5 +1,18 @@
import Route = require('route-parser');
const route = new Route('/users/:id');
// $ExpectType false | { [x: string]: string; }
const matched = route.match('/users/42'); // => { id: '42' }
// $ExpectType string | false
const reversed = route.reverse({ id: 42 });
// $ExpectType Route<{ id: number; }>
const route0 = new Route<{id: number}>('/users/:id');
// $ExpectType string | false
route0.reverse({id: 1});
// $ExpectType false | { id: string; }
route0.match('/users/:id');
// $ExpectType Route<{ slug: string; }>
const route1 = new Route<{slug: string}>('/posts/:slug');
// $ExpectType string | false
route1.reverse({slug: "hello"});