1. 程式人生 > >TypeScript入門知識五(面向對象特性二)

TypeScript入門知識五(面向對象特性二)

開發 func var ons inter 約定 pub 資源 new

1.泛型(generic)

參數化的類型,一般用來限制集合的內容

class Person {
  constructor(private name: string) {

  }

  work() {

  }
}
var worker: Array<Person> = [];//這裏指定數組中只能放Person類創建的對象

worker[0] = new Person("zhang san");

2.接口interface

用來建立某種代碼約定,使得其他開發者在調用某個方法或者創建新的類時必須遵循接口所定義的代碼約定。

(一)//接口聲明屬性,
  interface IPerson {
    name: string;
    age: number;
  }
//接口當做參數
  class Person {
    constructor(public config:IPerson) {

  }
  }
//在實例化一個類的時候,必須傳入參數
  var p1 = new Person({
    name: "zhang san",
    age: 18
  })

(二)接口聲明方法

//接口聲明屬性,
  interface Animal {
    eat();
  }
//實現接口關鍵字implements
  class Sheep implements Animal {
    eat() { //必須實現

    }
  }

(三)模塊(Module)

模塊可以幫助開發者將代碼分割為可重用的單元。開發者可以自己決定將模塊中的那些資源(類、方法、變量)暴露出去供外部使用,哪些資源只在模塊內使用。一般一個模塊就是一個文件

模塊主要是兩個關鍵字 exprot (導出)  import(導入)

文件 a.ts

export function fun1 () {

  console.log("輸出");

}

在文件 b.ts中引用

import { fun1} from ".a";

fun1();//調用

TypeScript入門知識五(面向對象特性二)