首页 > 解决方案 > 流星 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;

我现在似乎在工作,但是由于我对打字稿世界还很陌生,我想知道,这是否是正确的做法?!

标签: javascripttypescriptmeteor

解决方案


TypeScript 让您可以this像这样定义类型:

function f(this: ThisType) {}

有关更多信息,请参见此处:https ://www.typescriptlang.org/docs/handbook/functions.html

在这种特定情况下,您可以添加

this: Meteor.MethodThisType

runindex.d.ts 中的方法签名:

run: (this: Meteor.MethodThisType, args: { [key: string]: any; }) => void;

它并不完全完整,因为 ValidatedMethod 定义了几个额外的参数(例如this.name),但您可以根据需要添加这些参数。


推荐阅读