TypeScript基本介紹

前言

本文主要介紹TypeScript的基本知識,想深刻了解還得去看官方文檔html

這裏有一個本身用TypeScirpt編寫的工具庫,歡迎你們使用和互相學習,有時間會寫下文章講下如何開發和發佈本身的工具庫。git

什麼是TypeScript

TypeScript是Javascript的超集,並添加可選的靜態類型和類別,但瀏覽器沒法識別,因此要經過工具轉換爲Javascript代碼才能夠在瀏覽器上運行。github

爲何要用TypeScript

使用TypeScript能夠更好地編寫和維護代碼,由於它能夠指定變量的類型,更容易知道這個變量是什麼類型和擁有什麼屬性,而且它在編譯階段就會檢查出錯誤,提前發現錯誤的時間,而且不少編輯器對TypeScript有很好的支持,會有代碼提示,提升開發效率。數組

基礎類型

  • boolean
  • number
  • string
  • Array
let nums: number[] = [1, 2, 3];
let strings: Array<string> = ['str'];
複製代碼
  • enum
enum Color {Red, Green, Blue}  // Color = [0, 1, 2];
let c: Color = Color.Green;  // 1
複製代碼
  • any
  • void
  • nullundefined
  • never

接口

對象類型

interface Shape {
  readonly type: string;  // 只讀屬性
  color?: string;  // 可選屬性
  area: number;
  setColor(color: string): void;
  [prop: string]: any;  // 其餘屬性
}
複製代碼

函數類型

interface createShape {
    (square: Shape): Shape;
}
複製代碼

類類型與繼承接口

interface Square extends Shape {  // 繼承於Shape接口
  width: number;
  height: number;
  [prop: string]: any;  // 其餘屬性
}

interface ShapeConstructor {  // 構造器函數結構
  new(shape: Shape): Shape;
}

interface CircleInterface extends Shape {
  radius: number;
}

class Shape implements Shape {  // 產生Shape類型的類
  readonly type = 'shape';  // 只讀屬性只能在初始化時賦值
  color?: string;
  area: number;
  
  constructor(shape: Shape) {
    this.color = shape.color;
  }
  setColor(color: string) {
    this.color = color;
  }
}

class Square extends Shape implements Square {
  readonly type = 'square';  // 只讀屬性只能在初始化時賦值
  width: number;
  height: number;

  constructor(square: Square) {
    super(square);

    this.width = square.width;
    this.height = square.height;
    this.area = square.width * square.height;
  }
}

class Circle extends Shape implements CircleInterface {
  readonly type = 'circle';
  radius: number;
}

function createNewShape(ctor: ShapeConstructor, shape: Shape): Shape {
  return new ctor(shape);
}
複製代碼

泛型

泛型容許咱們能夠靈活地在調用期間才指定類型或由TS推斷類型。瀏覽器

function createArray<T> (): ()=> T[] {
    return ()=> [];
}

const createNumberArray = createArray<number>();
const numberArray = createNumberArray();

numberArray.push(1);
numberArray.push('1');  // 報錯,由於上面以指定數組爲數字類型
複製代碼
相關文章
相關標籤/搜索