Skip to content

Way to detect whether a callable has type parametersΒ #61838

Open
@mhofman

Description

@mhofman

πŸ” Search Terms

conditional type detect callable type parameter

βœ… Viability Checklist

⭐ Suggestion

I'm looking for some way to detect if a callable type is generic and has type parameters.

LLMs are hallucinating an answer that would be nice if it worked:

type HasTypeParameter<T extends (...args: any[]) => any> =
  T extends <G>(...args: any[]) => any ? true : false;

πŸ“ƒ Motivating Example

I have a utility type that wants to map the return value of a callable. However because as far as I know it's not possible to map a type-parametrized callable keeping its parametrization, we prefer to bail out in this case and maintain the original type.

Roughly it looks like

type MappedCallable<T extends Callable> = HasTypeParameter<T> extends true 
  ? T
  : (...args: Parameters<T>) => MappedResult<ReturnType<T>>;

πŸ’» Use Cases

I can achieve this detection in some case where the type of the callable is incompatible with a mapped callable were its type parameters inferred as any.

type LimitedHasTypeArgument<T extends (...args: any[]) => any> =
  ((...args: Parameters<T>) => ReturnType<T>) extends T ? false : true

However this doesn't work in some more complex cases (still trying to get a minimal repro).

I cannot think of other workarounds, which is forcing us to forego the result type mapping completely.

Of course having a way to keep the callable type-parametrization in the result mapping would be even better.

The specific use case is to map all callable in the result, including object methods, to callables returning a promise, while maintaining other parts of their signature.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions