如何通过JSDoc正确推断对象的构造函数类型?
解决方案:用JSDoc泛型与条件类型实现精准类型推断
要让JSDoc正确推断ParseType的返回类型,核心是利用泛型模板和条件类型断言,针对不同输入分支定义对应的返回类型,无需硬编码具体类。
1. 定义泛型条件类型
通过@typedef结合条件类型,为不同输入场景匹配对应的返回类型:
/** * @typedef {T extends Function & { prototype: object } * ? T * : T extends object * ? T['constructor'] * : T extends string * ? StringConstructor * : T extends number * ? NumberConstructor * : T extends boolean * ? BooleanConstructor * : T extends symbol * ? SymbolConstructor * : T extends bigint * ? BigIntConstructor * : never} ParseTypeReturn<T> */
这个类型会自动根据输入T匹配返回值:
- 若
T是带对象原型的函数,返回T本身 - 若
T是对象(非null),返回其构造函数类型 - 若
T是原始类型,返回对应的包装对象构造函数
2. 为函数添加泛型JSDoc注释
在ParseType上声明泛型参数,并使用上述类型作为返回值:
/** * @template T * @param {T} value * @returns {ParseTypeReturn<T>} */ function ParseType(value) { // 分支1:带对象原型的函数 if (typeof value === 'function' && typeof value.prototype === 'object') { return value; } // 分支2:非null对象 if (typeof value === 'object' && value !== null) { return value.constructor; } // 分支3:原始类型/箭头函数等,返回包装构造函数 return Object(value).constructor; }
验证推断效果
测试典型场景,JSDoc能精准推断返回类型:
// 自定义类实例:返回 typeof MyCustomType class MyCustomType {} const inst = new MyCustomType(); const type1 = ParseType(inst); // 推断为 typeof MyCustomType // 字符串:返回 StringConstructor const type2 = ParseType('test'); // 推断为 StringConstructor // 带原型的普通函数:返回函数本身 function Foo() {} const type3 = ParseType(Foo); // 推断为 typeof Foo // 箭头函数(无prototype):返回 FunctionConstructor const arrowFn = () => {}; const type4 = ParseType(arrowFn); // 推断为 FunctionConstructor
内容的提问来源于stack exchange,提问作者KLASANGUI
相关产品推荐
相关产品推荐

