Set type for function parameters?

后端 未结 12 1834
醉话见心
醉话见心 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 19:16

    Maybe a helper function like this. But if you see yourself using such syntax regularly, you should probably switch to Typescript.

    function check(caller_args, ...types) {
        if(!types.every((type, index) => {
            if(typeof type === 'string')
                return typeof caller_args[index] === type
            return caller_args[index] instanceof type;
        })) throw Error("Illegal argument given");
    }
    
    function abc(name, id, bla) {
       check(arguments, "string", "number", MyClass)
       // code
    }
    

提交回复
热议问题