如何在打字稿中设置“this”关键字的上下文

问题描述 投票:0回答:1

我有以下方法将代码库迁移到打字稿,其结构如下:

  1. mongo 集合的简单模式定义
  2. 一个单独的文件,其中存在特定集合元素实例的所有帮助程序

在代码中它看起来像这样: 架构:

const schema = new SimpleSchema({......});
type schemaType = { ..... }; // This is added by me as simple schema doesn't give typescript types

现在我有了helpers.ts:

const helpers = {
  helper1() { this.prop1 }; // prop1 is defined in `schemaType`
  helper2() { this.prop2 * this.prop3 }; // prop2 and prop3 are defined in `schemaType`
}

const helpersType = typeof helpers; // This will give all inferred types for helpers.

现在的问题是

this.prop1
this.prop2
this.prop3
会抛出打字稿错误,因为它不知道对象的上下文迟早会拥有这些道具。

那么我该如何处理呢?

我尝试向

helpers
对象添加类型,但它需要完整的类型定义或根本不需要类型才能使推断类型编译起作用。

typescript typescript-typings
1个回答
0
投票

您可以通过在参数中为

this
指定类型,向 TypeScript 提供有关执行函数的上下文的提示,如下所示:

interface Schema {
    prop1: string;
    prop2: number;
    prop3: number;
}

const helpers = {
    helper1(this: Schema) { this.prop1 },
    helper2(this: Schema) { this.prop2 * this.prop3 },
}

TypeScript 游乐场

© www.soinside.com 2019 - 2024. All rights reserved.