简体   繁体   中英

Does Typescript set interface properties in the Class Constructor?

In the Typescript documentation on interfaces , under "Class Types," the following example is given:

interface ClockInterface {
    currentTime: Date;
}

class Clock implements ClockInterface {
    currentTime: Date = new Date();
    constructor(h: number, m: number) { }
}

The line immediately below "class Clock..." that begins "currentTime:..." seems to imply that if I do var something = new Clock() , my something variable will have the currentTime attribute accessible on it, ie something.currentTime .

This confuses me, because of the following line from the MDN documentation on Javascript Classes :

Instance properties must be defined inside of class methods

The example they give:

class Rectangle {
  constructor(height, width) {    
    this.height = height;
    this.width = width;
  }
}

The implication is that the following code would be invalid:

class Rectangle {
  height: 23, 
  width: 45,
  constructor(height, width) {    
  }
}

My confusion: The example code in the Typescript documentation does not assign currentTime in the constructor. Is that step missing from their example, or does their syntax imply that "by the way, properties defined directly on the class are magically given a value, in the constructor?" If that's the case, what happens if you set a given value in the constructor on your own, "manually?"

class Clock implements ClockInterface {
    currentTime: Date = new Date();
    constructor(h: number, m: number) { }
}

The constructor is run and then any properties that are assigned defaults are wired up so currentTime is assigned after the constructor has been called.

This allows syntax like

class MyClass {
  myProperty = this.myService.serviceProperty;

  constructor(private myService: Myservice) {}
}

Marking constructor paramaters as private, protected or public auto assigns them as properties of the class and you don't need to do

this.property = paramater

in the constructor. TypeScript syntax is different that JavaScript but awesome once you get used to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM