index.d.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * Handle values based on a field.
  3. *
  4. * @template {InvalidHandler} [Invalid=InvalidHandler]
  5. * @template {UnknownHandler} [Unknown=UnknownHandler]
  6. * @template {Record<string, Handler>} [Handlers=Record<string, Handler>]
  7. * @param {string} key
  8. * Field to switch on.
  9. * @param {Options<Invalid, Unknown, Handlers>} [options]
  10. * Configuration (required).
  11. * @returns {{unknown: Unknown, invalid: Invalid, handlers: Handlers, (...parameters: Parameters<Handlers[keyof Handlers]>): ReturnType<Handlers[keyof Handlers]>, (...parameters: Parameters<Unknown>): ReturnType<Unknown>}}
  12. */
  13. export function zwitch<
  14. Invalid extends InvalidHandler = InvalidHandler,
  15. Unknown extends UnknownHandler = UnknownHandler,
  16. Handlers extends Record<string, Handler> = Record<string, Handler>
  17. >(
  18. key: string,
  19. options?: Options<Invalid, Unknown, Handlers> | undefined
  20. ): {
  21. (...parameters: Parameters<Handlers[keyof Handlers]>): ReturnType<
  22. Handlers[keyof Handlers]
  23. >
  24. (...parameters: Parameters<Unknown>): ReturnType<Unknown>
  25. unknown: Unknown
  26. invalid: Invalid
  27. handlers: Handlers
  28. }
  29. /**
  30. * Handle a value, with a certain ID field set to a certain value.
  31. * The ID field is passed to `zwitch`, and it’s value is this function’s
  32. * place on the `handlers` record.
  33. */
  34. export type Handler = (...parameters: any[]) => any
  35. /**
  36. * Handle values that do have a certain ID field, but it’s set to a value
  37. * that is not listed in the `handlers` record.
  38. */
  39. export type UnknownHandler = (value: unknown, ...rest: any[]) => any
  40. /**
  41. * Handle values that do not have a certain ID field.
  42. */
  43. export type InvalidHandler = (
  44. value: unknown,
  45. ...rest: any[]
  46. ) => void | null | undefined | never
  47. /**
  48. * Configuration (required).
  49. */
  50. export type Options<
  51. Invalid extends InvalidHandler = InvalidHandler,
  52. Unknown extends UnknownHandler = UnknownHandler,
  53. Handlers extends Record<string, Handler> = Record<string, Handler>
  54. > = {
  55. /**
  56. * Handler to use for invalid values.
  57. */
  58. invalid?: Invalid | undefined
  59. /**
  60. * Handler to use for unknown values.
  61. */
  62. unknown?: Unknown | undefined
  63. /**
  64. * Handlers to use.
  65. */
  66. handlers?: Handlers | undefined
  67. }