javascript函数类型检查需在运行时手动验证参数类型,常用typeof判断基础类型(如string、number),用严格相等检查undefined或null,避免instanceof等复杂方案,以轻量明确的方式提前暴露错误。

JavaScript 本身是动态类型语言,函数参数没有编译期类型约束,但你可以在运行时通过手动检查 + 断言来增强健壮性,避免隐式错误。关键不是“模拟 TypeScript”,而是用轻量、明确、可调试的方式提前暴露问题。
基础参数存在性与类型断言
最常见需求:确保某个参数传了,且是期望的类型(如 string、number、object)。推荐用 typeof 和严格相等判断,避免 instanceof 或 Object.prototype.toString 的过度复杂化。
- 检查必填参数是否存在:
if (arg === undefined)或if (arguments.length - 检查基本类型:
typeof arg === 'string'、typeof arg === 'number'(注意typeof null === 'object',需单独处理) - 检查对象/数组:
arg !== null && typeof arg === 'object' && !Array.isArray(arg);数组用Array.isArray(arg)
封装可复用的断言工具函数
避免每个函数里重复写 if-throw,抽一个简短的 assert 工具更清晰:
function assert(condition, message) {
if (!condition) throw new TypeError(`[Assertion Error] ${message}`);
}
<p>function processData(name, age) {
assert(typeof name === 'string' && name.trim(), 'name must be a non-empty string');
assert(typeof age === 'number' && Number.isInteger(age) && age > 0, 'age must be a positive integer');
// 正常逻辑...
}</p>
这样错误信息明确,调用栈干净,也方便后续替换成开发环境才启用的条件断言(比如用 process.env.NODE_ENV !== 'production' 包裹)。
处理可选参数与默认值结合校验
ES6 默认参数只解决“没传时给什么值”,不解决“传了但类型错”的问题。建议先设默认值,再统一校验:
function fetchUser(id, options = {}) {
assert(typeof id === 'number', 'id must be a number');
assert(typeof options === 'object' && options !== null, 'options must be a plain object');
assert(typeof options.timeout === 'number' || options.timeout === undefined, 'options.timeout must be a number if provided');
// ...
}
对嵌套结构(如 options?.retry?.max),不要在断言里层层可选链判断,先解构或提前提取再校验,保持断言语句简洁可读。
配合 JSDoc 提升协作与 IDE 支持
纯 JS 中加 JSDoc 注释,虽不执行检查,但能被 VS Code、WebStorm 等识别,提供参数提示和基础类型预警:
/**
* 计算矩形面积
* @param {number} width - 宽度,必须大于 0
* @param {number} height - 高度,必须大于 0
* @returns {number}
*/
function area(width, height) {
assert(typeof width === 'number' && width > 0, 'width must be a positive number');
assert(typeof height === 'number' && height > 0, 'height must be a positive number');
return width * height;
}
这相当于为 JS 加了一层“文档即契约”,开发者看注释就知道要传什么,IDE 能高亮类型不匹配,运行时断言兜底——三者互补,不重不漏。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











