ts-path-params
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

Path Params

Description

This module is utility module to replace path with params and infer the params from the path

Table Of Content


Example

CodeSandbox


Usage

Default

generatePath('/users/:userId', { userId: 1 }); // "/users/1"
type Params = PathVariable<'/users/:userId'> // { userId: string | number }

Customizing

const PathParamsPattern = {
  Default: createParamsPattern(':'),
  NextJSRoute: createParamsPattern('[', ']')
}
const generatePath = createPathGenerator(
  PathParamsPattern.Default,
  PathParamsPattern.NextJSRoute
)

generatePath('/users/:userId', { userId: 1 });
generatePath('/users/[userId]', { userId: 1 });
type Params = PathVariable<'/users/[userId]', typeof PathParamsPattern.NextJSRoute>

API

generatePath(path, params)

generatePath replaces path with params

  generatePath('/user/:userId', { userId: 1 });

createParamsPattern(prefix, postfix?)

return value is ParamPattern and used for createPathGenerator

  • /user/:userId => createParamsPattern(':')
  • /user/[userId] => createParamsPattern('[', ']')

createPathGenerator(...patterns)

createPathGenerator creates the generatePath function.
Created function replaces path by pattern

  const genreatePath = createPathGenerator(
    createParamsPattern(':'),
    createParamsPattern('[', ']')
  )
  genreatePath('/user/:userId', { userId: 1 });
  genreatePath('/user/[userId]', { userId: 1 });

type PathVariable<Path, Pattern?>

PathVariable infers the type from the path.

  type MyParams = PathVariable<'/user/:userId'>; 
  // { userId: string | number }

  const pattern = createParamsPattern('[', ']');
  type MySecondParams = PathVariable<'/user/[userId]', typeof pattern> 
  // { userId: string | number }

Package Sidebar

Install

npm i ts-path-params

Weekly Downloads

2

Version

1.0.0

License

MIT

Unpacked Size

5.47 kB

Total Files

6

Last publish

Collaborators

  • ehgus6887