Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define class property types in typescript?

I'm using ES6 classes in typescript with the following:

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

I get back this error, though it still seems to compile:

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

If I define the type:

this.ip: string = ip;

I get back:

';' expected.

How should I format the class to get rid of both errors?

like image 243
Philip Kirkbride Avatar asked Oct 28 '25 08:10

Philip Kirkbride


2 Answers

Either declare the property on the class first:

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

Or declare it on the constructor parameter (the preferred approach), just add an access modifier (public or private) to the parameter to indicate it is a property:

class Camera {
    constructor(public ip: string) {
        // note no explicit assignment
    }
}
like image 200
Jeff Mercado Avatar answered Oct 31 '25 01:10

Jeff Mercado


You have tried to access the property "ip" without definng it in the class itself. The constructer(ip){} is called when you call the Camera class and it search for the ip property.Since you have not defined it in the class gives an error

use this way. best wishes.

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

  constructor(ip) {
    this.ip = ip;
  }
}
like image 30
Chanaka Fernando Avatar answered Oct 30 '25 23:10

Chanaka Fernando



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!