镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Type for arbitrary number of function parameters of specified types #4338

Description

I'd like to have a type for a function which takes in zero or more parameters, and then use the type for the parameters, e.g.

// Note: the syntax below of course doesn't do what I'm looking for, something like (params: ...args: T) would be closer
let f = (params: T) => (params2: T) => 0;

// these should be legal:
f(5)(3);
f("foo")("bar");
f(5, "foo")(3, "bar");

// these should be illegal
f(5)("bar");
f("foo")(3);
f(5, 3)("foo", "bar");

This is useful in e.g. typing the spread function here:
DefinitelyTyped/DefinitelyTyped@3eb67c9

I need to use the ...args: any[], which is not quite what I'm looking for.

In essence, the type I want to use is [A?, B?, C?, ...], or maybe something like Params<T> if such an interface would exist.

Activity

  1. JsonFreeman commented on Aug 24, 2015

    @JsonFreeman
    Contributor

    Looks like you want something that allows a variable number of parameters with arbitrary types, but then captures them so they can be repeated in another signature. I think you may find a relevant discussion at #3622 (comment) and #3870.

  2. benliddicott commented on Sep 7, 2015

    @benliddicott

    Do you actually need an infinite number of parameters? If in practice you top out at something like ten or twenty then this might be a good pattern:

        function f<T1>(a1: T1): (a1: T1) => any;
        function f<T1, T2>(a1: T1, a2: T2): (a1: T1, a2: T2) => any;
        function f<T1, T2, T3>(a1: T1, a2: T2, a3: T3): (a1: T1, a2: T2, a3: T3) => any;
        function f<T1, T2, T3, T4>(a1: T1, a2: T2, a3: T3, a4: T4): (a1: T1, a2: T2, a3: T3, a4: T4) => any;
        function f<T1, T2, T3, T4, T5>(a1: T1, a2: T2, a3: T3, a4: T4, a5: T5): (a1: T1, a2: T2, a3: T3, a4: T4, a5: T5) => any;
       // Continue the theme until you are sure you have met requirements. Maybe ten or twenty arguments?
        function f(...params: any[]):any {
    
        }
    
    
    

    It's flexible, doesn't require new syntax, and works today.

  3. JsonFreeman commented on Sep 8, 2015

    @JsonFreeman
    Contributor

    That is indeed the recommended pattern to use today.

  4. mhegazy commented on Feb 22, 2016

    @mhegazy
    Contributor

    looks like a duplicate of #1773

  5. locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions