Set type for function parameters?

后端 未结 12 1826
醉话见心
醉话见心 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:09

    Use typeof or instanceof:

    const assert = require('assert');
    
    function myFunction(Date myDate, String myString)
    {
        assert( typeof(myString) === 'string',  'Error message about incorrect arg type');
        assert( myDate instanceof Date,         'Error message about incorrect arg type');
    }
    

提交回复
热议问题