javascript - 将变量清除为 this.x = x 时,Typescript 会抛出错误

标签 javascript typescript

我在其中有一个和一个构造函数。构造函数得到一个值 x 作为参数,我想用

为类声明一个变量
this.x = x 

但是 typescript 会抛出一个错误:

TS2339: Property 'x' does not exist in type 'myClass'

有谁知道如何在不声明每个变量的情况下解决这个问题,比如 "private x: number;"--> "this.x = x"

最佳答案

如果你有一个构造函数参数,你可以只声明一个访问修饰符使它成为一个字段,你甚至不需要执行赋值(typescript会为你做)

class C {
    constructor(public x: number) {} // can also be private or protected instead of public
    m() {
        this.x = 10;
    }
}
new C(1).x // ok, x is declared and is 1

关于javascript - 将变量清除为 this.x = x 时,Typescript 会抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57001577/

相关文章:

javascript - for语句循环小写输出

Javascript:最大字符串长度 Chrome

javascript - 如何在替换列表中的值时修复 "undefined"项目

angular - 如何创建组合来自两个不同功能模块的数据的 NGRX 选择器?

javascript - typescript :如何说一个变量是时刻类型的?

typescript - 为什么 TypeScript 不能从过滤后的数组中推断类型?

typescript - 来自 API 错误的数据 [无法解析 UserService : (? 的所有参数]。

typescript - 尝试使用空 ts 项目初始化 webpack 时出错

javascript - 具有 Codeigniter 表单验证的 Bootstrap 模态

javascript - 结合 anchor 、url 变量和切换可见性