javascript - 流星 1.10.2 打字稿 ValidatedMethod - this.userId
问题描述
我正在为流星打字稿和mdg:ValidatedMethod
.
我使用了This Repo中的 @types用于mdg:ValidatedMethod
.
让我们假设这个流星代码没有 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 时,找不到打字稿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(),
});
}
});
我检查了第一个示例中的类型并this
在@type-definition 中添加了 -ref 运行方法,这意味着我将第 17 行从
run: (args: { [key: string]: any; }) => void;
至
run: (this: Meteor.MethodThisType, args: { [key: string]: any; }) => void;
我现在似乎在工作,但是由于我对打字稿世界还很陌生,我想知道,这是否是正确的做法?!
解决方案
TypeScript 让您可以this
像这样定义类型:
function f(this: ThisType) {}
有关更多信息,请参见此处:https ://www.typescriptlang.org/docs/handbook/functions.html
在这种特定情况下,您可以添加
this: Meteor.MethodThisType
到run
index.d.ts 中的方法签名:
run: (this: Meteor.MethodThisType, args: { [key: string]: any; }) => void;
它并不完全完整,因为 ValidatedMethod 定义了几个额外的参数(例如this.name
),但您可以根据需要添加这些参数。
推荐阅读
- r - 强制表中的值属性(R 脚本)
- java - 在 Eclipse 上运行斯坦福作业的问题
- c# - 有没有办法为任何 System.IndexOutOfRangeException 消息创建通用 EventHandler?
- php - 在未通过身份验证时访问刀片在 Laravel 中显示为错误
- python-3.x - 可变默认参数允许访问来自其他类实例的数据
- javascript - 使 JS 宽度:toggle 有漂亮的动画
- javascript - 为什么 Firefox 忽略“不安全内联”csp 指令?
- oracle - 在 ORACLE 中创建作业
- java - 切换活动时保存活动状态
- javascript - 柯里化函数中第一个函数的命名约定