【问题标题】:Do I have to convert a JavaScript module to a TypeScript class to keep using 'this'?我是否必须将 JavaScript 模块转换为 TypeScript 类才能继续使用“this”?
【发布时间】:2022-11-22 09:07:26
【问题描述】:

我正在将 JavaScript 项目转换为 Typescript。
我有一个来自 require()-d 的旧模块文件主程序项目的文件。

这是简化的示例:

//required_module.js

const foo = require("bar");

module.exports = {
    start(myvar) {
        this.myvar = myvar;
        this.myfunc('str1');
        this.myfunc('str2');
    },
    myfunc(type) {
        const other = new foo.stuff;

        if (type === 'str1') {
            other.fn1(this.xbar(type));
        }
        else if (type === 'str2') {
            other.fn2('blahblah', this.xbar(type));
        }

        other.go();
    },
    xbar(type) {
        return this.myvar.asd(type);
    }
};

如您所见,这只是一个简单的 JS 模块文件(不是类),它多次使用 this,并且按预期工作。

但是,当我尝试将此模块转换为 TypeScript 模块时不创建类从中,当我尝试不同的方法时,我在 this 引用中遇到了不同类型的错误,例如:

Object is possibly 'undefined'.ts(2532)
'this' implicitly has type 'any' because it does not have a type annotation.ts(2683)
An outer value of 'this' is shadowed by this container.

创建类或 TypeScript 的唯一解决方案是否还允许以特定方式在类外部使用 this

【问题讨论】:

  • You probably don't have to convert it to a class,但你会过得更好:你将遇到动态添加属性(如myvar)或在无类型对象上调用方法的问题。 Typescript 不希望您将 JS 对象视为随机的属性包:already another data structure for that
  • 你能提供这些错误的打字稿示例吗?因为据我所知,它非常简单,而 Typescript 可以很好地处理它。 See playground
  • 我将较少关注转换为打字稿,而更多地关注转换为现代模块语法。如果您使用命名导出而不是对象方法,则不会有这些问题。但是,您将拥有一个有状态的、静态的、模块范围的 myvar 变量(就像您目前所做的那样),应该避免这种情况。代替单例,可以多次实例化的 class 可能是更好的方法。
  • 感谢大家提供的指导性 cmet 和 playground 示例!由于我是 TS 的新手,我在我的代码中犯了一些小的但非常自我误导的错误(通过过度思考和试验接口,名称空间)。我修复了我的代码,并会在我继续时牢记您的建议。

标签: javascript typescript class object


【解决方案1】:

根据有用的 cmets,答案是:

您可能不必将它转换为一个类,但您会过得更好:您将遇到动态添加属性(如 myvar)或调用无类型对象方法的问题。 Typescript 不希望您将 JS 对象视为随机的属性包:there's already another data structure for that
- 贾里德史密斯

我将较少关注转换为打字稿,而更多地关注转换为现代模块语法。如果您使用命名导出而不是对象方法,则不会有这些问题。但是,您将拥有一个有状态的、静态的、模块范围的 myvar 变量(就像您目前所做的那样),应该避免这种情况。可以多次实例化的类可能是更好的方法,而不是单例。
- 亚历克斯·韦恩

这个例子,简单转换后的代码在 TypeScript 中看起来像这样:

import foo from 'bar';

export default {
    myvar: 0,

    start(myvar: number) {
        this.myvar = myvar;
        this.myfunc('str1');
        this.myfunc('str2');
    },

    myfunc(type: 'str1' | 'str2') {
        const other = new foo.stuff;

        if (type === 'str1') {
            other.fn1(this.xbar(type));
        }
        else if (type === 'str2') {
            other.fn2('blahblah', this.xbar(type));
        }

        other.go();
    },

    xbar(type: string) {
        //...
    }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    相关资源
    最近更新 更多