【问题标题】:Left-hand side of assignment expression cannot be a constant or a read-only property赋值表达式的左侧不能是常量或只读属性
【发布时间】:2016-12-13 14:17:10
【问题描述】:

当我在我的 Express 服务器上使用这一行时,它在 TypeScript 1.x 中运行良好

mongoose.Promise = global.Promise;

(mongoose.Promise = global.Promise;的用法来自the mongoose document)

更新到 TypeScript 2.x 后,它在终端显示此错误,并且不允许我启动服务器。

赋值表达式的左侧不能是常量或 只读属性。

我该如何解决这个问题?谢谢

【问题讨论】:

    标签: express angular mongoose angular2-universal typescript2.0


    【解决方案1】:

    还有一种方法可以使用这种技术来维护类型检查和智能感知。

    import * as mongoose from "mongoose"; // same as const mongoose = require("mongoose");
    type mongooseType = typeof mongoose;
    (mongoose as mongooseType).Promise = global.Promise;
    // OR
    (<mongooseType>mongoose).Promise = global.Promise;
    

    这可能是一种有用的方法,可以使用模拟函数仅覆盖模块中的某些函数,而无需像 jest.mock() 这样的模拟框架。

    【讨论】:

      【解决方案2】:

      这是因为在es6 中,所有模块的变量都被视为常量

      https://github.com/Microsoft/TypeScript/issues/6751#issuecomment-177114001

      TypeScript 2.0 中修复了错误(未报告此错误)。

      由于mongoose 仍在使用commonjs - var mongoose = require("mongoose") - 而不是es6 导入语法(在分型中使用),您可以通过假设模块类型为any 来抑制错误.

      解决方法:

      (mongoose as any).Promise = global.Promise;
      

      【讨论】:

      • 谢谢!刚刚添加了另一种类似的方式:(&lt;any&gt;mongoose).Promise = global.Promise;
      猜你喜欢
      • 2018-05-04
      • 2021-05-07
      • 1970-01-01
      • 1970-01-01
      • 2015-07-07
      • 2017-05-28
      • 1970-01-01
      • 2018-10-08
      • 2016-11-24
      相关资源
      最近更新 更多