简体   繁体   English

Typescript是否在类构造函数中设置接口属性?

[英]Does Typescript set interface properties in the Class Constructor?

In the Typescript documentation on interfaces , under "Class Types," the following example is given: 接口Typescript文档中 ,在“类类型”下,给出以下示例:

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 . 紧接在“ class Clock ...”类下面的以“ currentTime:...”开始的行似乎暗示着,如果我执行var something = new Clock() ,我的something变量将具有可访问的currentTime属性,即something.currentTime

This confuses me, because of the following line from the MDN documentation on Javascript Classes : 这使我感到困惑,因为有关Javascript类的MDN文档中的以下行:

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. 我的困惑:Typescript文档中的示例代码未在构造函数中分配currentTime。 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. 运行构造函数,然后将分配给默认属性的所有属性连接起来,以便在调用构造函数后分配currentTime。

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. TypeScript语法与JavaScript有所不同,但是一旦您习惯它就很棒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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