typescript / expert
Snippet
ECMAScript Stage 3 Method Decorator for Parameter Validation
This snippet shows modern standard ECMAScript Stage 3 Method Decorators in TypeScript without experimental flags. It utilizes `ClassMethodDecoratorContext` with strictly typed generic `This`, `Args`, and `Return` type parameters to decorate methods and validate inputs at runtime.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function ValidateNonEmpty<This, Args extends [string, ...unknown[]], Return>(target: (this: This, ...args: Args) => Return,context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>) {const methodName = String(context.name);return function (this: This, ...args: Args): Return {if (!args[0] || args[0].trim().length === 0) {throw new Error(`Invalid argument in ${methodName}: string must not be empty`);}return target.apply(this, args);};}class UserRegistry {@ValidateNonEmptyregisterUser(username: string, role: string): string {return `Registered ${username} as ${role}`;}}
Breakdown
1
function ValidateNonEmpty<This, Args extends [string, ...unknown[]], Return>(...
Defines a type-safe decorator targeting methods whose first argument is guaranteed to be a string.
2
context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>
Leverages the official decorator context object to inspect metadata like the method name type-safely.
3
return function (this: This, ...args: Args): Return
Returns a wrapper replacement function preserving instance context and return type signature.
4
@ValidateNonEmpty
Applies the decorator directly to class methods using native Stage 3 decorator syntax.