我有以下方法将代码库迁移到打字稿,其结构如下:
在代码中它看起来像这样: 架构:
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
对象添加类型,但它需要完整的类型定义或根本不需要类型才能使推断类型编译起作用。
您可以通过在参数中为
this
指定类型,向 TypeScript 提供有关执行函数的上下文的提示,如下所示:
interface Schema {
prop1: string;
prop2: number;
prop3: number;
}
const helpers = {
helper1(this: Schema) { this.prop1 },
helper2(this: Schema) { this.prop2 * this.prop3 },
}