关于TypeScript:TypeScript-里的-class-field

7次阅读

共计 1674 个字符,预计需要花费 5 分钟才能阅读完成。

例子如下:

和这个知识点相干的 tsc 编译选项:strictPropertyInitialization

strictPropertyInitialization 设置管制是否须要在构造函数中初始化类字段。

正确做法:

class GoodGreeter {
  name: string;

  constructor() {this.name = "hello";}
}

请留神,该字段须要在构造函数自身中进行初始化。TypeScript 不会剖析您从结构函数调用的办法来检测初始化,因为派生类可能会笼罩这些办法并且无奈初始化成员。

class 成员须要在构造函数里进行初始化操作。如果在构造函数里调用其余函数,而后在这些其余函数里进行字段初始化,这样也不行。

如果肯定要这样做,即您打算通过构造函数以外的形式明确初始化字段(例如,可能内部库正在为您填充类的一部分),您能够应用明确赋值断言运算符,!:

class OKGreeter {
  // Not initialized, but no error
  name!: string;
}

如果一个 class field 设置为 readonly,这示意它只能在构造函数内被赋值。

子类构造函数的第一行语句,必须是 super() 函数调用;

什么是 TypeScript class 里的成员办法

精确定义:A function property on a class is called a method.

除了规范类型注解之外,TypeScript 不会向办法增加任何其余新内容。

须要留神的是,在 TypeScript 办法实现外部,必须用 this. 来拜访其成员变量。

下列代码里,m 办法外部,拜访的是 class 内部定义的类型为 number 的 x 变量,而不是 class 外部类型为 string 的变量。

let x: number = 0;

class C {
  x: string = "hello";

  m() {
    // This is trying to modify 'x' from line 1, not the class property
    x = "world";
Type 'string' is not assignable to type 'number'.Type 'string' is not assignable to type 'number'.
  }
}

class 的拜访其 accessors

class C {
  _length = 0;
  get length() {return this._length;}
  set length(value) {this._length = value;}
}

TypeScript 对拜访器有一些非凡的推理规定:

(1)如果 get 存在但没有 set,则该属性主动为只读
(2) 如果没有指定 setter 参数的类型,则依据 getter 的返回类型推断
(3)Getter 和 setter 必须具备雷同的成员可见性

对于 TypeScript class 继承和接口实现的一些坑

重要的是要了解 implements 子句只是查看类是否能够被视为接口类型。它基本不会扭转类的类型或其办法。一个常见的谬误起源是假如一个 implements 子句会扭转类的类型——它不会!

看这个例子:

interface Checkable {check(name: string): boolean;
}

class NameChecker implements Checkable {check(s) {
    // Notice no error here
    return s.toLowerCase() === "ok";}
}

const a = new NameChecker();

console.log(a.check('ok'));

语法错误:

起因是因为第 6 行代码里,咱们没有为 check 办法的参数 s 指明类型,因而其类型默认为 any. 这就和 interface Checkable 里定义的 check 办法的输出参数类型 string 不统一了。

解决办法:

同样,应用可选属性实现接口不会创立该属性:

interface A {
  x: number;
  y?: number;
}
class C implements A {x = 0;}
const c = new C();
c.y = 10;

解决办法:

更多 Jerry 的原创文章,尽在:” 汪子熙 ”:

正文完
 0