[英]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.