Skip to content

infer argument types for generic method decorator factory #39903

Closed
@rhyek

Description

@rhyek

Search Terms

TypedPropertyDescriptor generic method decorator arguments

Suggestion

I would like for a method decorator factory to be able to receive a callback as an argument whose own arguments mirror the method the decorator is being applied to.

Use Cases

I would like to write a custom memoize decorator for methods that allows me to provide a function which would return a cache key based on the original method's arguments.

Examples

function cached<TargetType extends Object, ArgumentsType extends any[], ReturnType = any>(cacheKey: (...args: ArgumentsType) => string) {
  return function(
    target: any,
    key: PropertyKey,
    descriptor: TypedPropertyDescriptor<(...params: ArgumentsType) => Promise<ReturnType>>
  ) {
    descriptor.value = async function(this: TargetType, ...args: ArgumentsType) {
      const _cacheKey = cacheKey(...args);
      const result = getFromCache(_cacheKey) ?? descriptor.value.apply(this, ...args);
      return result;
    }
  }
}

class Example {
  @cached(param1 => param1.toUpperCase()) // should know param1 is of type string
  async work(param1: string) {
    return networkRequest(param1);
  }
}

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DeclinedThe issue was declined as something which matches the TypeScript visionSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions