fastify / fastify-request-context

Request-scoped storage support, based on Asynchronous Local Storage (with fallback to cls-hooked)
MIT License
154 stars 15 forks source link

Stricter default context interface? #159

Closed voxpelli closed 1 year ago

voxpelli commented 1 year ago

Prerequisites

🚀 Feature Proposal

I would propose swapping this:

  export interface RequestContextData {
    [key: string]: any
  }

For plain:

  export interface RequestContextData {
  }

Motivation

This way someone like me who wants to get help ensuring I don't mistype any context names can use this plugin really strictly typed, and if someone wants to be lenient on the key names but strict with the types, then they could easily do:

declare module '@fastify/request-context' {
  interface RequestContextData {
    [key: string]: unknown
  }
}

And those who wants to have it like today can simply do:

declare module '@fastify/request-context' {
  interface RequestContextData {
    [key: string]: any
  }
}

By leaving out the default [key: string]: any it becomes possible to customize the type in ways otherwise not possible.

Example

No response

Uzlopak commented 1 year ago

interface bla { } is afaik disencouraged, because then you could assign everything to the variable. E.g.

interface A {
}

const emptyObject1:A = {} // works
const num1: A = 3 // works

interface B {
    [key:string]: any
}

const emptyObject2:B = {} // works
const num2: B = 3 // error
voxpelli commented 1 year ago
interface A {
  _?: never
}

Something like that would be preferable then? A sacrificial key to make it be interpreted as an object?

voxpelli commented 1 year ago

As can be seen in this TS Playground I think the empty interface works correctly for this module (and of course should never actually be empty in practice as any typed user will extend it):

Skärmavbild 2023-06-12 kl  00 05 42

kibertoad commented 1 year ago

sounds good to me. needs documentation and tsd tests