在打字稿中定义 class 属性 类型?

Define class property types in typescript?

我在打字稿中使用 ES6 classes:

class Camera {
    constructor(ip) {
        this.ip = ip;
    }
}

我找回了这个错误,虽然它似乎仍然可以编译

Property 'ip' does not exist on type 'Camera'.

如果我定义类型:

this.ip: string = ip;

我回来了:

';' expected.

我应该如何格式化 class 以消除这两个错误?

首先在 class 上声明 属性:

class Camera {
    ip: string;
    constructor(ip: string) {
        this.ip = ip;
    }
}

或者在构造函数参数上声明它(首选方法),只需在参数上添加访问修饰符(publicprivate)以表明它是一个 属性:

class Camera {
    constructor(public ip: string) {
        // note no explicit assignment
    }
}

您试图访问 属性 "ip" 而未在 class 本身中定义它。 当您调用相机 class 时会调用构造函数 (ip){} 并且它会搜索您尚未在 class 中定义的 ip property.Since 给出错误

这样使用。祝福。

class Camera {
 private ip: string;  // declare your variable first with the type

  constructor(ip) {
    this.ip = ip;
  }
}