繁体   English   中英

JSDoc 中条件属性的类型信息

[英]Type information for a conditional property in JSDoc

我正在通过 JSDoc 将 TypeScript 的类型信息添加到现有的 JavaScript 库中。 我有一个构造函数 function 可能会根据给定的参数的值设置属性:


/**
 * Settings you can use to configure an instance of an {@link ExampleClass}
 *
 * @typedef {Object} ExampleOptions
 * @property {true} [option] You can set this to `true` to make a property on an instance of {@link ExampleClass} exist. If you don't set it, that property won't exist
 */

/**
 * A thing that does stuff
 * 
 * @constructor
 * @param {ExampleOptions} [param] Options you can use to configure the new instance
 */
function ExampleClass(param) {
    if(param.option === true) {
        /**
         * A property that only exists based on the options given to this constructor
         *
         * @type {boolean}
         */
        this.property = true;
    }
}

我希望 TypeScript 会在外部将财产声明解释为property property?: boolean; ,但看起来它被解释为非可选的,并出现在我的编辑器的自动完成中,而无需提前检查它的存在。 理想情况下,我希望它是一个可选属性,您必须在使用它之前检查它,或者如果 TypeScript 可以以某种方式保证您已将{option: true}传递给构造函数。 我怎样才能使它工作?

你能不能只做

interface options {
   option? : boolean;
}

/**
 * A thing that does stuff
 * 
 * @constructor
 * @param {options} [param] Options you can use to configure the new instance
 */
function ExampleClass(param : options) {
    if(param.option === true) {
        /**
         * A property that only exists based on the options given to this constructor
         *
         * @type {boolean}
         */
        this.property = true;
    }
}

使用带有可选属性的@typedef预先声明 class 并将其设置为构造函数作为类型为{new () => ExampleClass}的变量。 这样,甚至可以将其声明为this定义的 class 并在构造函数 function 本身内完成代码。 如下所示:

/**
 * Settings you can use to configure an instance of an {@link ExampleClass}
 *
 * @typedef {Object} ExampleOptions
 * @property {true} [option] You can set this to `true` to make a property on an instance of {@link ExampleClass} exist. If you don't set it, that property won't exist
 */

/**
 * @typedef {object} ExampleClass
 * @prop {boolean} [property] A property that only exists based on the options given to this constructor
 */

/**
 * A thing that does stuff
 *
 * @constructor
 * @param {ExampleOptions} [param] Options you can use to configure the new instance
 * @this {ExampleClass}
 * @type {{new () => ExampleClass}}
 */
const ExampleClass = function (param) {
    if(param.option === true) {
        this.property = true;
    }
}

截屏

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM