我想使用在类的构造函数中定义的对象作为类本身函数中的类型。
我想做这样的事情,这样自动完成功能就可以工作:
class Collection {
constructor(schema) {
/**
* @typedef {schema} Schema
*/
// ...
}
/**
* @param {Schema} searchObj
*/
findOne(searchObj) {
// ...
}
这不起作用,因为该值是动态的,而不是静态的。
我想在构造函数中使用动态值“schema”作为类型,因此当用户初始化类时,类中的所有函数都可能需要与初始化时类型相同的参数。
const userCollection = new Collection({
name: String,
id: Number
})
userCollection.findOne({
name: "AngelCMHxD" // This should have autocompletion
})
我认为这是不可能的,即使使用
@template
:
/** @template T */
class Collection {
/**
* @param {T} schema
*/
constructor(schema) {
}
/**
* @param {T} searchObj
*/
findOne(searchObj) {
}
}
// Collection<{
// name: StringConstructor;
// id: NumberConstructor;
// }>
const userCollection = new Collection({
name: String,
id: Number
})
userCollection.findOne({
name: "AngelCMHxD" // expects StringConstructor, not string
})
因为您通过了
String
和 Number
,它们分别属于 StringConstructor
和 NumberConstructor
类型。如果你想让它工作,你必须传递 ""
和 0
,因此它被推断为 string
和 number
:
// Collection<{ name: string; id: number }>
const userCollection = new Collection({
name: "",
id: 0
})
您应该考虑使用 TypeScript,因为它的类型系统可以轻松地表示这一点。
您可以使用 @typedef 定义一次对象形状,然后多次重复使用它。
/**
* The complete Triforce, or one or more components of the Triforce.
* @typedef {Object} WishGranter~Triforce
* @property {boolean} hasCourage - Indicates whether the Courage component is present.
* @property {boolean} hasPower - Indicates whether the Power component is present.
* @property {boolean} hasWisdom - Indicates whether the Wisdom component is present.
*/