Typescript代碼執行個體解析__typescript

來源:互聯網
上載者:User
簡介:

TypeScript 是一種由微軟開發的自由和開源的程式設計語言,它是JavaScript的一個超集,擴充了JavaScript的文法。 文法特性 類 Classes 介面 Interfaces 模組 Modules 類型註解 Type annotations 編譯時間類型檢查Compile time type checking Arrow 函數 (類似 C# 的 Lambda 運算式) JavaScript 與 TypeScript 的區別

TypeScript 是 JavaScript 的超集,擴充了 JavaScript 的文法,因此現有的 JavaScript 代碼可與 TypeScript 一起工作無需任何修改,TypeScript 通過類型註解提供編譯時間的靜態類型檢查。
TypeScript 可處理已有的 JavaScript 代碼,並只對其中的 TypeScript 代碼進行編譯。 一、基礎類型 1、字串新特性

可以使用模版字串,它可以定義多行文本和內嵌運算式。 這種字串是被反引號包圍( `),並且以${ expr }這種形式嵌入運算式

let name: string = `Gene`;let age: number = 37;let sentence: string = `Hello, my name is ${ name }.I'll be ${ age + 1 } years old next month.`;
2、數組的使用

TypeScript像JavaScript一樣可以運算元組元素。 有兩種方式可以定義數組。 第一種,可以在元素類型後面接上 [],表示由此類型元素組成的一個數組:

let list: number[] = [1, 2, 3];

第二種方式是使用數組泛型,Array<元素類型>:

let list: Array<number> = [1, 2, 3];
3、枚舉

enum類型是對JavaScript標準資料類型的一個補充。 像C#等其它語言一樣,使用枚舉類型可以為一組數值賦予友好的名字。

enum Color {Red, Green, Blue}let c: Color = Color.Green;

可以手動賦值

enum Color {Red = 1, Green = 2, Blue = 4}let c: Color = Color.Green;

枚舉類型提供的一個便利是你可以由枚舉的值得到它的名字。 例如,我們知道數值為2,但是不確定它映射到Color裡的哪個名字,我們可以尋找相應的名字:

let colorName: string = Color[2];alert(colorName);

枚舉是在運行時真正存在的一個對象。 其中一個原因是因為這樣可以從枚舉值到枚舉名進行反向映射。

enum Enum {    A}let a = Enum.A;let nameOfA = Enum[a]; // "A"

有時候需求卻比較嚴格。 當訪問枚舉值時,為了避免產生多餘的代碼和間接引用,可以使用常數枚舉。 常數枚舉是在 enum關鍵字前使用const修飾符。

const enum Enum {    A = 1,    B = A * 2}
4、Any

有時候,我們會想要為那些在編程階段還不清楚類型的變數指定一個類型。 這些值可能來自於動態內容,比如來自使用者輸入或第三方程式碼程式庫。 這種情況下,我們不希望類型檢查器對這些值進行檢查而是直接讓它們通過編譯階段的檢查。 那麼我們可以使用 any類型來標記這些變數:

let notSure: any = 4;notSure = "maybe a string instead";notSure = false; // okay, definitely a boolean

你可能認為 Object有相似的作用,就像它在其它語言中那樣。 但是 Object類型的變數只是允許你給它賦任意值 - 但是卻不能夠在它上面調用任意的方法,即便它真的有這些方法 5、Void

某種程度上來說,void類型像是與any類型相反,它表示沒有任何類型。 當一個函數沒有傳回值時,你通常會見到其傳回值類型是 void:

function warnUser(): void {    alert("This is my warning message");}
6、Null 和 Undefined 和 Never

作用不大 7、類型斷言

類型斷言有兩種形式。 其一是“角括弧”文法:

let someValue: any = "this is a string";let strLength: number = (<string>someValue).length;

let strLength: number = (someValue).length;
另一個為as文法:

let someValue: any = "this is a string";let strLength: number = (someValue as string).length;
二、參數新特性 參數類型 預設值 選擇性參數
function test(a:string,b?:string,c:string="jojo"){    console.log(a);    console.log(b);    console.log(c);}test("aaa");
三、變數聲明

let和const是ES6裡新特性 1、let和const都有塊級範圍 塊或for之外不可訪問 不能被聲明前讀或寫 不可重定義 內層屏蔽外層,應避免 2、不同

const雖然與let有相同的塊級範圍規則,但不可重新賦值。 四、函數新特性 1、Rest和Spread

//傳入任意多的參數function test(...args){    args.forEach(function (arg) {        console.log(arg);    })}console.log(1,2,3,4,5,6);//傳的參數不固定,但真正傳入的按照函數來定function test2(a,b,c){    console.log(a);    console.log(b);    console.log(c);}var args1 = [1,2,3,4,5];test2(...args1);//雖然報錯,但是產生的js檔案可實現功能//在angular4的項目中ng build --prod時會自動進行AOT先行編譯,//ts代碼報錯會無法編譯通過,因此不能在有先行編譯的項目中使用
2、Generator

控制函數執行過程,手動暫停和恢複代碼執行

function* test(){    console.log("start");    yield ;    console.log("start");}
3、解構函式distructuring
function getStock(){    return {        code:"IBM",        price:100    }}var {code,price} = getStock();console.log(code);console.log(price);function getStock2(){    return {        code:"ibm",        price:{            price1:600,            price2:400        }    }}var {code:codex,price:{price2}} = getStock2();console.log(codex);console.log(price2);var arr1 = [1,2,3,4];var [a,b]=arr1;console.log(a);console.log(b);var [, ,c,d]=arr1;console.log(c);console.log(d);var [m,n,...others]=arr1;console.log(m);console.log(n);console.log(others);
四、運算式與迴圈 1、箭頭運算式
var fun1 = () =>{}var arr1 = [1,2,3,4];console.log(arr1.filter((value)=> value%2==0 ));//////最主要的作用是正確指向thisfunction getNum() {    this.i=1;    setInterval(() => {        console.log(this.i);    },1000);}
2、of迴圈

of迴圈與in迴圈的區別:

var arr1 = [1,2,3,4];for(var n in arr1){    console.log(arr1[n]);}for(var n of arr1){    console.log(n);}
五、物件導向的特性 1、類
class Person{    constructor(public name:string){    }    eat(){        console.log(this.name);    }}var p = new Person("frank");p.eat();

繼承Person類–extends

class Employee extends Person {    code:string;    work(){        console.log(this.name+" is working");    }}var e = new Employee("eric");e.work();

super–子類調父類調建構函式

class Employee2 extends Person {    constructor(name:string,code:string){        super(name);        this.code = code;    }    code:string;    work(){        super.eat();    }}var e2 = new Employee2("eric","0");e2.work();
2、泛型

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

class Person{    constructor(public name:string){    }    eat(){        console.log(this.name);    }}var workers : Array<Person> = [];
3、介面
interface IPerson{    name:string;    age:number;}class Person{    constructor(public config:IPerson){    }}var p = new Person({    name:"frank",    age:18});//implementsinterface animal{    eat();}class tiger implements animal{    eat(){        console.log("i like meat");    }}class sheep implements animal{    eat(){        console.log("i like grass");    }}
4、模組

可重用的單元,開發人員自己決定模組中哪些資源(類、變數、函數)暴露出去給外部使用,哪些自己使用

module1.ts:

export var prop1;export function fun1(){};export class Person{};

module2.ts:

import {prop1,fun1,Person} from './module1';var p = new Person();var prop = prop1;export class ModuleTest{    constructor(private props:prop1){    }}
5、註解 annoation

註解:為程式的元素(類、方法、變數)添加更直觀的說明,這些說明與程式的商務邏輯無關,而是供指定的工具或架構使用。

import { Component, OnInit } from '@angular/core';@Component({  selector: 'platform',  templateUrl: './platformAccount.component.html',})export class test{         ......}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.