🤖 Merge PR #65715 cls-hooked: Add strong typing for namespace key/values by @LucianBuzzo

This change allows you to parmaterize `createNamespace`, allowing for
strong typing of the `get` and `set` methods.

Signed-off-by: Lucian Buzzo <lucian.buzzo@gmail.com>
This commit is contained in:
Lucian Buzzo
2023-06-14 14:38:24 +01:00
committed by GitHub
parent dba969edcc
commit 58d57ca87a
3 changed files with 30 additions and 7 deletions

View File

@@ -17,7 +17,7 @@ function bindLater(callback: (x: number) => number) {
bindLater((x: number) => {
return x;
})(123); // passing argument 'abc' should get compile error
})(123); // passing argument 'abc' should get compile error
const session2 = cls.getNamespace('my session')!;
session2.get('user');
@@ -42,3 +42,23 @@ appNamespace.exit(context);
appNamespace.enter(context);
appNamespace.get('requestId');
appNamespace.exit(context);
interface MyContext {
foo: string;
bar: number;
}
const typedNameSpace = cls.createNamespace<MyContext>('typed');
typedNameSpace.set('foo', 'foo');
typedNameSpace.set('bar', 123);
// @ts-expect-error
typedNameSpace.set('bar', 'foo');
// @ts-expect-error
typedNameSpace.set('foo', 123);
const retrievedNameSpace = cls.getNamespace<MyContext>('typed');
if (retrievedNameSpace) {
retrievedNameSpace.get('foo');
}

View File

@@ -1,17 +1,18 @@
// Type definitions for cls-hooked 4.3
// Project: https://github.com/jeff-lewis/cls-hooked
// Definitions by: Leo Liang <https://github.com/aleung>
// Lucian Buzzo <https://github.com/LucianBuzzo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import { EventEmitter } from 'events';
export interface Namespace {
export interface Namespace<N = Record<string, any>> {
active: any;
set<T>(key: string, value: T): T;
get(key: string): any;
set<K extends keyof N = keyof N>(key: K, value: N[K]): N[K];
get<K extends keyof N = keyof N>(key: K): N[K];
run(fn: (...args: any[]) => void): void;
runAndReturn<T>(fn: (...args: any[]) => T): T;
runPromise<T>(fn: (...args: any[]) => Promise<T>): Promise<T>;
@@ -22,7 +23,9 @@ export interface Namespace {
exit(context: any): void;
}
export function createNamespace(name: string): Namespace;
export function getNamespace(name: string): Namespace | undefined;
// eslint-disable-next-line no-unnecessary-generics
export function createNamespace<N = Record<string, any>>(name: string): Namespace<N>;
// eslint-disable-next-line no-unnecessary-generics
export function getNamespace<N = Record<string, any>>(name: string): Namespace<N> | undefined;
export function destroyNamespace(name: string): void;
export function reset(): void;

View File

@@ -3,4 +3,4 @@
"rules": {
"npm-naming": false
}
}
}