Class

扩展了ES6中的Class。

访问修饰符

Class提供了public、private、protected访问修饰符。
所有成员默认都是public的,可以在任何地方访问。
private 成员只允许在声明的类中访问,即使是在其派生类中也不能被访问。(但可通过暴露get()和set()在外部读取修改)
protected成员则在声明的类及其派生类都可以被访问。构造函数也可以被标记成protected, 这意味着这个类不能在包含它的类外被实例化,但是能被继承。

  1. class BaseUser {
  2. public name: string;
  3. private age: number;
  4. protected hobby: string;
  5. protected constructor (name: string, age: number ) {
  6. this.name = name;
  7. this.age = age;
  8. };
  9. shoutout() {
  10. return `The user is ${this.name}, he is ${this.age} years old.`;
  11. }
  12. }
  13. // const newUser = new BaseUser('Tom', 28); // error
  14. class User extends BaseUser {
  15. city: string;
  16. constructor(name, age) {
  17. super(name, age);
  18. this.city = 'hangzhou';
  19. }
  20. introduce() {
  21. return `His hobby is ${this.hobby}. He live in ${this.city}`;
  22. }
  23. }
  24. const user = new User("Alan", 17);
  25. console.log(user.shoutout());
  26. console.log(user.introduce());
  27. console.log(user.name);
  28. // console.log(user.age); // error
  29. // console.log(user.hobby); // error
  30. console.log(user.city);

readonly

你可以使用readonly关键字将Class属性设置为只读,但只读属性必须在声明时或构造函数里被初始化。

  1. class Octopus {
  2. readonly name: string;
  3. readonly numberOfLegs: number = 8;
  4. constructor (theName: string) {
  5. this.name = theName;
  6. }
  7. }
  8. let dad = new Octopus("Man with the 8 strong legs");
  9. dad.name = "Man with the 3-piece suit"; // error! name is readonly.

typeof取类的类型

  1. class Greeter {
  2. static standardGreeting = "Hello, there";
  3. greeting: string;
  4. greet() {
  5. if (this.greeting) {
  6. return "Hello, " + this.greeting;
  7. }
  8. else {
  9. return Greeter.standardGreeting;
  10. }
  11. }
  12. }
  13. let greeter1: Greeter; // 去类的实例类型
  14. greeter1 = new Greeter();
  15. console.log(greeter1.greet());
  16. let greeterMaker: typeof Greeter = Greeter; // 取类的类型
  17. greeterMaker.standardGreeting = "Hey there!";
  18. let greeter2:Greeter = new greeterMaker();
  19. console.log(greeter2.greet());

把类作为接口使用

类定义会创建两个东西:类实例的类型和一个构造函数。 我们可以创建一个只包含实例类型的类,然后在使用接口的地方使用该类(该类不能创建构造函数)。

  1. class Point {
  2. x: number;
  3. y: number;
  4. }
  5. interface Point3d extends Point {
  6. z: number;
  7. }
  8. let point3d: Point3d = {x: 1, y: 2, z: 3};

函数类型

完整的函数类型

  1. // 此处=>并非箭头函数而是指示函数返回值
  2. // 两边定义的名称可不同,只要对应位置的类型相同即可
  3. let myFunc: (baseValue: number, increase: number) => number =
  4. function(x: number, y: number) { return x+y };
  5. // 也可以使用接口定义
  6. interface MyFunc {
  7. (x: number, y: number): number;
  8. }
  9. let myFunc2: MyFunc = function(x: number, y: number) { return x+y };

在使用变量赋值定义匿名函数时,若自定义了一边的类型,则编译器会自动推断另一边的类型。通常情况下无需两边都定义。

与ES类似,函数定义也支持默认参数及剩余参数。

  1. function func1(arg1: string = '11', ...restArgs: string[]) {
  2. // do sth
  3. }

函数定义也支持重载

  1. let suits = ["hearts", "spades", "clubs", "diamonds"];
  2. function pickCard(x: {suit: string; card: number; }[]): number;
  3. function pickCard(x: number): {suit: string; card: number; };
  4. function pickCard(x): any {
  5. // Check to see if we're working with an object/array
  6. // if so, they gave us the deck and we'll pick the card
  7. if (typeof x == "object") {
  8. let pickedCard = Math.floor(Math.random() * x.length);
  9. return pickedCard;
  10. }
  11. // Otherwise just let them pick the card
  12. else if (typeof x == "number") {
  13. let pickedSuit = Math.floor(x / 13);
  14. return { suit: suits[pickedSuit], card: x % 13 };
  15. }
  16. }
  17. let myDeck = [{ suit: "diamonds", card: 2 }, { suit: "spades", card: 10 }, { suit: "hearts", card: 4 }];
  18. let pickedCard1 = myDeck[pickCard(myDeck)];
  19. alert("card: " + pickedCard1.card + " of " + pickedCard1.suit);
  20. let pickedCard2 = pickCard(15);
  21. alert("card: " + pickedCard2.card + " of " + pickedCard2.suit);

泛型

用于定义可重用组件。
如何定义泛型,在对象属性名或函数名后跟,T为泛型变量。
注意,无法创建泛型枚举和泛型命名空间。

  1. function func3<U>(arg: U): U {
  2. return arg;
  3. }
  4. class GenericNumber<T> {
  5. zeroValue: T;
  6. add: (x: T, y: T) => T;
  7. }
  8. let myGenericNumber = new GenericNumber<number>();
  9. myGenericNumber.zeroValue = 0;
  10. myGenericNumber.add = function(x, y) { return x + y; };

泛型接口

  1. // 接口属性定义为泛型
  2. interface GenericIdentityFn {
  3. <T>(arg: T): T;
  4. }
  5. function identity<T>(arg: T): T {
  6. return arg;
  7. }
  8. let myIdentity: GenericIdentityFn = identity; // 参数类型不确定
  9. // 暴露接口的参数为泛型,可传入一个类型约束其它成员
  10. interface GenericIdentityFn2<T> {
  11. (arg: T): T;
  12. }
  13. function identity2<T>(arg: T): T {
  14. return arg;
  15. }
  16. let myIdentity: GenericIdentityFn2<number> = identity2; // 参数类型只能为number

泛型约束

使用extends可定义泛型约束

  1. function func4<T, U extend Arg<T>>(a: T, b: U):void {
  2. // do sth
  3. }

在泛型里使用类类型

  1. class Animal {
  2. numLegs: number;
  3. }
  4. class Lion extends Animal {
  5. keeper: ZooKeeper;
  6. }
  7. function findKeeper<A extends Animal, K> (a: {new(): A;
  8. prototype: {keeper: K}}): K {
  9. return a.prototype.keeper;
  10. }
  11. findKeeper(Lion).nametag; // typechecks!