首页 > 解决方案 > Typescript 是否在类构造函数中设置接口属性?

问题描述

有关接口的 Typescript 文档中,在“类类型”下,给出了以下示例:

interface ClockInterface {
    currentTime: Date;
}

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

“class Clock...”下面以“currentTime:...”开头的行似乎暗示如果我这样做var something = new Clock(),我的something变量将具有currentTime可访问的属性,即something.currentTime.

这让我感到困惑,因为MDN 文档中关于 Javascript Classes的以下行:

实例属性必须在类方法中定义

他们给出的例子:

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

这意味着以下代码将无效:

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

我的困惑:Typescript 文档中的示例代码没有在构造函数中分配 currentTime。他们的示例中是否缺少该步骤,或者他们的语法是否暗示“顺便说一句,直接在类上定义的属性在构造函数中被神奇地赋予了值?” 如果是这种情况,如果您自己“手动”在构造函数中设置给定值会发生什么?

标签: javascripttypescriptclass

解决方案


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

运行构造函数,然后连接分配默认值的任何属性,以便在调用构造函数后分配 currentTime。

这允许语法像

class MyClass {
  myProperty = this.myService.serviceProperty;

  constructor(private myService: Myservice) {}
}

将构造函数参数标记为私有、受保护或公共自动将它们分配为类的属性,您不需要这样做

this.property = paramater

在构造函数中。TypeScript 语法与 JavaScript 不同,但一旦你习惯了它就很棒。


推荐阅读