javascript - 将 ES6 类转换为 Typescript 类

标签 javascript node.js reactjs typescript ecmascript-6

我有以下 ES6 类。

class Http {
    isFormData;
    url;
    token;
    data;

    constructor() {
        this.isFormData = false;
        this.url = '';
        this.token = '';
        this.data = {};
    }

    /** Set url */
    setUrl(url: string) {
        this.url = url;
        return this;
    }

    /** Set data */
      setData(data: Object) {
        this.data = data;
        return this;
    }
}

export default new Http();

我想将其设为 typescript 类。我尝试过,但某些属性未正确识别。我怎样才能使它成为 typescript 类?

最佳答案

您需要指定属性的类型。我还建议您将它们设为私有(private):

class Http {
    private isFormData: boolean;
    private url: string;
    private token: string;
    private data: Object;

    constructor() {
        this.isFormData = false;
        this.url = '';
        this.token = '';
        this.data = {};
    }

    /** Set url */
    setUrl(url: string) {
        this.url = url;
        return this;
    }

    /** Set data */
    setData(data: Object) {
        this.data = data;
        return this;
    }
}

export default new Http();

关于javascript - 将 ES6 类转换为 Typescript 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60182520/

相关文章:

javascript - 我可以设置在 Chrome 中显示的 PDF 对象的文件名吗?

javascript - 在存在多个类的情况下单击时获取标签的数据键

node.js - 运行 npm 脚本时如何抑制输出

node.js - 在用于系统测试的开源项目中保护 travis ci 环境变量

javascript - 如何在 React 中为状态变化的 span 元素设置动画?

javascript - Webpack 别名指向未配置 webpack 的父目录

javascript - 将 UNIX 时间戳差异转换为分钟

javascript - 用重音改变字符

node.js - MongoDB Mongoose 错误: Cannot call `collection.aggregate()` before initial connection is complete

javascript - 如何在不点击 react 元素的情况下检测时间