[vs code]Type Script簡介二

TypeScript Interface、Class、Generics

本篇將針對TypeScript的介面、物件、泛型...等更深入的介紹。


正文開始 :

Interface :

基本範例

interface ICar{
	carname: string;
	carage: number;
}

function MyFunc(carobj : ICar){
	console.log(carobj);
}

let o = MyFunc({carname:'BMW',carage:15});

其中如果carage要改成非必填的話可以改成下面這樣

carage?: number;

如果要把interface設定成此兩個屬性以外使用者可以另外再塞入其他屬性的話

為了要排除編譯器執行過度屬性檢查

請在carage下面加入一行

[propName: string]: any;

這句話的意思是說我設定屬性質是any,

而因為屬行名稱一定是string,所以前半段的propName就設定其形態是string

後半段因為不知道使用者會傳入什麼樣的型態資料,故使用any來撰寫

Class :

基本範例

class Car{
	//constructor(private _carname){}
	private _carname;
	constructor(carname){
		this._carname = carname;
	}
	private _carage;
	get carage(){
		return this._carage;
	}
	set carage(age){
		this._carage = age;
	}
	
	getCarinfo(){
		console.log(`The car name is ${this._carname}.\n
		The car age is ${this._carage}.`); 
	}
}

var o = new Car('BMW');
o.carage = 18;
o.getCarinfo();

class的建構式一定是constructor的function

如果要宣告一個private的屬性去接建構式帶進來的值可以如畫面3~6行所示

也可以直接濃縮成第二行這樣寫法

class裡面如果要宣告的屬性是public則不用特別去打,其餘兩種均需要特別註明

另外Type Script也提供了類似C#的get set語法

使用如上範例所示

以下附上轉出成JS的語法

var Car = (function () {
    function Car(carname) {
        this._carname = carname;
    }
    Object.defineProperty(Car.prototype, "carage", {
        get: function () {
            return this._carage;
        },
        set: function (age) {
            this._carage = age;
        },
        enumerable: true,
        configurable: true
    });
    Car.prototype.getCarinfo = function () {
        console.log("The car name is " + this._carname + ".\n\n\t\tThe car age is " + this._carage + ".");
    };
    return Car;
}());
var o = new Car('BMW');
o.carage = 18;
o.getCarinfo();

export & import :

每一個檔案都是一個module

每個module都可以做export的動作

語法如下 :

export class Car{
	//constructor(private _carname){}
	private _carname;
	constructor(carname){
		this._carname = carname;
	}
	private _carage;
	get carage(){
		return this._carage;
	}
	set carage(age){
		this._carage = age;
	}
	
	getCarinfo(){
		console.log(`The car name is ${this._carname}.\n
		The car age is ${this._carage}.`); 
	}
}

每個檔案都可以匯入module

匯入的語法如下

import {Car} from './car'; //ES6
import {Car as cars} from './car';
import * as cars from './car';
import express = require('express'); //ES5

其餘的部分,因尚未深入了解,故就不再此介紹了...