Home > Blockchain >  How to specify the return value of a function based on the value of a parameter
How to specify the return value of a function based on the value of a parameter

Time:09-08

I have something like the following:

function myFunctionBuilder(/* Parameters Irrelevant to MWE */) {
   return function (argument: Targument): [ -1 | 0 | 1, Targument ] {
    // ...
   }
}

and I would like to add parameter1 to myFunctionBuilder which would allow one to specify a number to be returned in place of -1 | 0 | 1, under certain conditions, and I wondered if it's possible to add this user-specified value in the return type? The following is incorrect, but (hopefully!) illustrates what I'm trying to achieve:

function myFunctionBuilder(parameter1: number, /* Parameters Irrelevant to MWE */) {
   return function (argument: Targument): [ -1 | 0 | 1 | parameter1, Targument ] {
    // ...
   }
}

Is this possible, or do I just have to broaden the return type to any number? i.e.:

function myFunctionBuilder(parameter1: number, /* Parameters Irrelevant to MWE */) {
   return function (argument: Targument): [ number, Targument ] {
    // ...
   }
}

CodePudding user response:

A generic can be thought of as a way to "store" the type of a parameter that was given:

function myFunctionBuilder<Parameter1 extends number>(parameter1: Parameter1, /* Parameters Irrelevant to MWE */) {
   return function (argument: Targument): [ -1 | 0 | 1 | Parameter1, Targument ] {
    // ...
   }
}

extends number is a generic constraint. It means that parameter1 must be a number.

  • Related