Set type for function parameters?

后端 未结 12 1838
醉话见心
醉话见心 2020-11-30 18:37

Is there a way to let a javascript function know that a certain parameter is of a certain type?

Being able to do something like this would be perfect:



        
12条回答
  •  长情又很酷
    2020-11-30 18:55

    You can implement a system that handles the type checks automatically, using a wrapper in your function.

    With this approach, you can build a complete declarative type check system that will manage for you the type checks . If you are interested in taking a more in depth look at this concept, check the Functyped library

    The following implementation illustrates the main idea, in a simplistic, but operative way :

    /*
     * checkType() : Test the type of the value. If succeds return true, 
     * if fails, throw an Error
     */
    function checkType(value,type, i){
      // perform the appropiate test to the passed 
      // value according to the provided type
      switch(type){
        case Boolean : 
          if(typeof value === 'boolean') return true;
          break;
        case String : 
          if(typeof value === 'string') return true;
          break;
        case Number : 
          if(typeof value === 'number') return true;
          break;
        default :
          throw new Error(`TypeError : Unknown type provided in argument ${i+1}`);
      }
      // test didn't succeed , throw error
      throw new Error(`TypeError : Expecting a ${type.name} in argument ${i+1}`);
    }
    
    
    /*
     * typedFunction() : Constructor that returns a wrapper
     * to handle each function call, performing automatic 
     * arguments type checking
     */
    function typedFunction( parameterTypes, func ){
      // types definitions and function parameters 
      // count must match
      if(parameterTypes.length !== func.length) throw new Error(`Function has ${func.length} arguments, but type definition has ${parameterTypes.length}`);
      // return the wrapper...
      return function(...args){
        // provided arguments count must match types
        // definitions count
        if(parameterTypes.length !== args.length) throw new Error(`Function expects ${func.length} arguments, instead ${args.length} found.`);
        // iterate each argument value, and perform a
        // type check against it, using the type definitions
        // provided in the construction stage
        for(let i=0; i{
      return a+b;
    });
    
    // call the function, with an invalid second argument
    myFunc(123, '456')
    // ERROR! Uncaught Error: TypeError : Expecting a Number in argument 2

提交回复
热议问题