[英]meteor 1.10.2 typescript ValidatedMethod - this.userId
我正在努力解决 meteor typescript 和mdg:ValidatedMethod
。
我将This Repo中的 @types 用于mdg:ValidatedMethod
。
让我们假设这个 meteor 代码没有 ValidateMethod:
const addLink = Meteor.methods({
'links.add'({ title,url }) {
new SimpleSchema({
title: { type: String },
url: {type: String}
}).validate({ title,url });
if (!this.userId) {
//throw an error!
}
LinksCollection.insert({
title,
url,
createdAt: new Date(),
});
}
});
这里一切正常, if (this.userId) {
但是,当我现在更改为 ValidatedMethod 时,typescript 找不到this.userId
const addLink = new ValidatedMethod({
name: 'links.add',
validate: new SimpleSchema({
title: { type: String },
url: {type: String}
}).validator(),
run({title,url}) {
if (!this.userId) { //Here typescript can't find this.userId
//throw an error!
}
LinksCollection.insert({
title,
url,
createdAt: new Date(),
});
}
});
我检查了第一个示例中的类型并在@type-definition 中添加了this
-ref 运行方法,这意味着我将第 17 行从
run: (args: { [key: string]: any; }) => void;
至
run: (this: Meteor.MethodThisType, args: { [key: string]: any; }) => void;
我现在似乎在工作,但是由于我对 typescript 世界还很陌生,我想知道这是否是正确的做法?!
TypeScript 允许您定义 this 的类型, this
所示:
function f(this: ThisType) {}
请参阅此处了解更多信息: https://www.typescriptlang.org/docs/handbook/functions.html
在这种特定情况下,您可以添加
this: Meteor.MethodThisType
到 index.d.ts 中的run
方法签名:
run: (this: Meteor.MethodThisType, args: { [key: string]: any; }) => void;
它并不完全完整,因为 ValidatedMethod 定义了几个额外的参数(例如this.name
),但您可以根据需要添加这些参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.