TypeScript基礎知識彙總

ts 基礎知識

  1. 基礎數據類型
    • number
      let num: number = 2; let num1: number = 0x0;
      複製代碼
    • string
      let num: string = "2";
      複製代碼
    • boolean
      let num: boolean = true;
      複製代碼
    • Array
      let num: number[] = [1, 2, 3]; let num1: Array<string> = ["1", "2"]
      複製代碼
    • 元組
      let num: [string, number] = ["1", 2];   // 沒用過
      複製代碼
    • enum
      enum Color {
              Red,
              Blue
          }
          Console.log(Color.Red)  // 0
          Console.log(Color[0])   // "Red"
      複製代碼
    • void
      // 用於標識方法返回值的類型,表示該方法沒有返回值
          function hello(): void {
              alert("Hello Runoob");
          }
      複製代碼
    • null
      // null 表示對象值缺失
      複製代碼
    • undefined
      // undefined 用於初始化變量爲一個未定義的值
      複製代碼
    • never
      // never 是其它類型(包括 null 和 undefined)的子類型,表明從不會出現的值
          let x: never;
          let y: number;
          // 運行正確,never 類型能夠賦值給 never類型
          x = (()=>{ throw new Error('exception')})(); // 運行正確,never 類型能夠賦值給 數字類型 y = (()=>{ throw new Error('exception')})(); 複製代碼
    • any
      // any 任意數據類型
          let a: any;
          a = 12;
          a = "asdasd";
          a = true;
      複製代碼
  2. TypeScript 變量聲明
    • TypeScript 變量的命名規則:
      • 變量名稱能夠包含數字和字母
      • 除了下劃線 _ 和美圓 $ 符號外,不能包含其餘特殊字符,包括空格。
      • 變量名不能以數字開頭。
    • 變量的聲明
      let [變量名] : [類型] = 值;
      複製代碼
    • 類型斷言
      // <類型>值
         class TestClass {
             public name: string = "12";
         }
         function test (a: number | string) :void {
             let b: string = <string>a;
         }
         // 值 as 類型
         function test1 (a: any) :void {
             console.log((a as TestClass).name);
         }
         // 斷言以後纔會有提示
         interface ITest {
             a (): void;
         }
         interface ITest1 {
             b (): void;
         }
         function tt (param: ITest | ITest1) : void {
             (param as ITest1).b;
             (<ITest>param).a;
         }
         // 強行斷言 不建議這麼寫
         let a: number = 12;
         let b: string = <number>a // Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
         let c: string = <number><any>a;
         let d: string = <number><unknown>a;
         // 遊戲裏面通用的消息模塊(包含枚舉 斷言)
         // 數值枚舉
         enum AllNum {
             hp_min = 0,
             marrid_age = 18
         }
      
         // 消息ID枚舉
         enum MsgId {
             hero_msg,
             monster_msg,
         }
      
         // 消息類型
         class MsgType {
             public static HERO_MESSAGE = "hero_message";
             public static MONSTER_MESSAGE = "monster_message";
         }
      
         // 全部模塊都須要實現的接受消息的接口
         interface IReceiveMessage {
             receive (msg: IMsgData): void;
         }
      
         // 消息數據結構
         interface IMsgData {
             msgName: string;
             msgId: number;
             data: any;
         }
      
         // 角色數據
         interface IHeroMessageData {
             name: string;
             age: number;
             isAlive: boolean;
         }
      
         // 怪物數據
         interface IMonsterMessageData {
             id: string;
             hp: number;
             isAlive: boolean;
         }
      
         // 角色模塊
         class ModuleHero implements IReceiveMessage{
             public isMarried: boolean = false;
             receive (msg: IMsgData) : void {
                 if (msg.msgName == MsgType.HERO_MESSAGE) {
                     let data = msg.data as IHeroMessageData;
                     if (data.age <= AllNum.marrid_age) {
                     this.isMarried = false;
                         return;
                     }
                     this.isMarried = true;
                 }
             }
         }
      
         // 怪獸模塊
         class ModuleMonster implements IReceiveMessage {
             receive (msg: IMsgData) : void {
                 if (msg.msgName == MsgType.MONSTER_MESSAGE) {
                     let data = msg.data as IMonsterMessageData;
                     if (data.hp <= AllNum.hp_min) {
                         console.log("The Monster is died");
                         return;
                     }
                 }
             }
         }
      
         // 消息中心
         class MessageCenter {
             public modules: IReceiveMessage[] = [];
             // 訂閱消息-- 僅限窗口存在的時候
             public subscribe (module: IReceiveMessage) : void {
                 this.modules.push(module)
             }
      
             // 接受到服務器消息
             public receiveMsg (msg : IMsgData) : void {
                 this.broadcast(msg)
             }
      
             // 廣播消息
             public broadcast (msg : IMsgData) : void {
                 let _length: number = this.modules.length;
                 if (_length <= 0) return;
                 for (let i : number = 0; i < _length; i ++) {
                     let item: IReceiveMessage = this.modules[i];
                     item.receive(msg);
                 } 
             }
         }
      
         // 主入口
         class Main {
             public msgCenter: MessageCenter;
             constructor () {
                 this.msgCenter = new MessageCenter();
      
                 let hero = new ModuleHero();
                 let monster = new ModuleMonster();
      
                 this.msgCenter.subscribe(hero);
                 this.msgCenter.subscribe(monster);
      
                 let msg: IMsgData = {
                     msgName: MsgType.HERO_MESSAGE,
                     msgId: 1,
                     data: {
                         name: "lacy",
                         age: 18,
                         isAlive: true
                     }
                 }
      
                 this.msgCenter.receiveMsg(msg);
             }
         }
      複製代碼
  3. TypeScript 運算符 不講都同樣。
  4. TypeScript 條件語句 跟js的都是同樣的。
  5. TypeScript 循環
    // 跟js都是同樣的,惟一不一樣是須要寫數據類型
        let _length: number = 12;
        for (let i : number; i < _length; i ++) {
            console.log(i);
        }
    複製代碼
  6. TypeScript 函數
    // function 函數名 () :函數返回值類型 {}
        function test () :number {
            return 12;
        }
        /** * 函數參數的類型 * ?: 可選參數 * 可選參數必定放在全部參數的最後面 */
        function test1 (param1: string, param2: number = 12, param3?: boolean, ...param4: string[]) :void {
            console.log(param1);
            console.log(param2);
            console.log(param3);
            console.log(param4);    // ["a", "d"];
        }
        test("11"); 
        test("11", 12, true, "a", "d")
    複製代碼
  7. TypeScript 聯合類型 能夠經過管道(|)將變量設置多種類型,賦值時能夠根據設置的類型來賦值
    let a: string | number;
        a = "12";
        a = 12;
        let a: string[] | number[]; // 這是定義了兩種類型的數組,可是每個數組內部的類型必須是一致的
        let b: (string | number)[]; // 定義了一個數組,數組裏面的數據能夠是number或者string
        a = [1, "12"];  // 報錯
        b = [1, "12"];  // 正確
    複製代碼
  8. TypeScript 接口 接口是一系列抽象方法的聲明,是一些方法特徵的集合,這些方法都應該是抽象的,須要由具體的類去實現 通常用來定義數據結構,或者指定方法須要具備哪些API
    • TypeScript 接口定義以下
    interface interface_name { 
        }
        // 由於接口只聲明,沒有具體實現,接口裏面的方法都是public的
        interface ITest {
            write (): void;
        }
        // 一個類能夠實現多個接口
        interface ITest1 {
            load (): void;
        }
        class TT implements ITest, ITest1{
            public write (): void {}
            public load (): void {}
        }
         // 能夠多繼承
        interface IDemo extends ITest, ITest1{
            demo (): void;
        }
        class TT implements IDemo{
            public write (): void {}
            public load () :void {}
            demo () : void {}
        }
        // 委託的實現
        /** * ts 裏經常使用的委託實現方案 */
        interface ILanguageDelegate {
            (name : string) : void;
        }
    
        class TestDelegate
        {
            constructor () {
    
            }
            public chineseDelegate (name : string) :void {
                console.log("Chinese name is ==>" + name);
            }
    
            public englishDelegate (name : string) :void {
                console.log("English name is ==>" + name);
            }
    
            public wrongDelegate (age : number) :void {
                console.log(age);
            }
            
            public tDelegate (name : string, fun: ILanguageDelegate) {
                fun(name);
            }
    
            public main () :void {
                this.tDelegate("1231", this.chineseDelegate);
                // this.TDelegate("1231", this.wrongDelegate); // 這樣寫就會報錯,說參數簽名不對
            }
        }
    複製代碼
  9. TypeScript 類
    • TypeScript 類定義方式以下
    class class_name { 
            // 類做用域
        }
        class Demo{
            public st: string;
            public static staticA: string;
            private num: number;
            private static staticB: number;
            constructor () {
                this.st = "12";
                this.num = 12;
                console.log(Demo.staticA);  // 這樣都是沒問題的
                console.log(Demo.staticB);  // 這樣都是沒問題的
            }
            public write (): void {}
            public static staticWrite () :void {
                console.log(this.staticA);  // 這樣都是沒問題的
                console.log(this.staticB);  // 這樣都是沒問題的
                console.log(this.st)    // 這些屬性都是訪問不到的
            }
            private load () :void {}
            private static staticLoad () :void {
                console.log(this.staticA);  // 這樣都是沒問題的
                console.log(this.staticB);  // 這樣都是沒問題的
            }
            protected del () : void {}
        }
    
            (function test () {
                let d = new Demo();
                console.log(d.st);  // 一共就能訪問這兩個屬性
                console.log(d.write);  // 一共就能訪問這兩個屬性
            })()
            console.log(Demo.staticA);
            console.log(Demo.staticWrite);
            console.log(Demo.staticB);  // 訪問不到
        // 典型的單例寫法
        class GameController {
            private static _isntance: GameController;
            public static getInstance () : GameController {
                if (!this._isntance) {
                    this._isntance = new GameController();
                }
                return this._isntance;
    
            }
        }
        // 繼承的demo
        interface IObserver {
            openView() : void;
        }
        class BaseClass {
            public _name: string;
            private _age: number;
            constructor ($name: string, $age: number) {
                this._name = $name;
                this._age = $age;
            }
    
            public createChildren () :void {}
    
            private childrenCreated () :void {}
    
            public prepareDestroy () :void {}
    
            public destroy () :void {}
            // 受保護函數只有子類能夠訪問
            protected del () :void {
            
            }
        }
    
        class ChildClass extends BaseClass implements IObserver {
            constructor ($name: string, $age: number) {
                super($name, $age);  // 必須實現父類的構造函數
                this.main();
            }
            private main () : void {
                console.log(this._name);    
                console.log(this.del);
                let test: ChildClass = new ChildClass("21", 12);
                test.destroy();
                test.del(); // 這個時候是能夠訪問到的
            }
            public openView () : void {
                
            }
            public createChildren () : void {
                super.createChildren();
            }
    
            public prepareDestroy () : void {
                // 這些改寫成本身的邏輯就能夠了
            }
        }
    
        let a: ChildClass = new ChildClass("21", 12);
        a.del() // 沒有這個函數
        // 抽象類
        abstract class Demo {
            abstract init () :void;     // 抽象方法是子類必須實現的
    
            public main () : void {}
    
            public create () : void {}
    
            public created () : void {}
    
            public upDate () : void {}
    
            public destroy () : void {}
        }
        class ChildClass extends Demo{
            public init () : void {
    
            }
        }
    複製代碼
  10. TypeScript 命名空間 命名空間一個最明確的目的就是解決重名問題。
    namespace Util {
        export namespace Utils {
            export class ControllerUtil {
                public control () : void {
                    console.log(" control ")
                }
            }
        }
        export class DebugUtil {
            public static log (msg: string) : void {
                console.log(msg)
            }
        }
    }
    
    Util.DebugUtil.log("12313");
    let ctl: Util.Utils.ControllerUtil = new Util.Utils.ControllerUtil();
    ctl.control();
    複製代碼
  11. TypeScript 模塊
    /// <reference path = "IShape.ts" /> 
        export interface IShape { 
            draw(); 
        }
        // Circle.ts
        import shape = require("./IShape"); 
        export class Circle implements shape.IShape { 
            public draw() { 
                console.log("Cirlce is drawn (external module)"); 
            } 
        }
    複製代碼
  12. TypeScript 聲明文件
    • 爲何須要聲明文件 當在開發過程當中要引用其餘第三方的 JavaScript 的庫,雖然經過直接引用能夠調用庫的類和方法,沒法使用TypeScript 諸如類型檢查等特性功能,經過引用這個聲明文件,就能夠借用 TypeScript 的各類特性來使用庫文件了
    • 聲明文件 聲明文件以 .d.ts 爲後綴,例如:test.d.ts
    • 具體寫法
    declare module Runoob { 
            export class Calc { 
                doSum(limit:number) : number; 
            }
        }
        // 這是我以前導出的protobuf.d.ts文件的內容
        // protobuf.d.ts
        import * as $protobuf from "protobufjs";
        /** Properties of a Person. */
        export interface IPerson {
    
            /** Person name */
            name?: (string|null);
    
            /** Person age */
            age?: (number|null);
        }
    
        /** Represents a Person. */
        export class Person implements IPerson {
    
            /**
            * Constructs a new Person.
            * @param [properties] Properties to set
            */
            constructor(properties?: IPerson);
    
            /** Person name. */
            public name: string;
    
            /** Person age. */
            public age: number;
    
            /**
            * Creates a new Person instance using the specified properties.
            * @param [properties] Properties to set
            * @returns Person instance
            */
            public static create(properties?: IPerson): Person;
    
            /**
            * Encodes the specified Person message. Does not implicitly {@link Person.verify|verify} messages.
            * @param message Person message or plain object to encode
            * @param [writer] Writer to encode to
            * @returns Writer
            */
            public static encode(message: IPerson, writer?: $protobuf.Writer): $protobuf.Writer;
    
            /**
            * Encodes the specified Person message, length delimited. Does not implicitly {@link Person.verify|verify} messages.
            * @param message Person message or plain object to encode
            * @param [writer] Writer to encode to
            * @returns Writer
            */
            public static encodeDelimited(message: IPerson, writer?: $protobuf.Writer): $protobuf.Writer;
    
            /**
            * Decodes a Person message from the specified reader or buffer.
            * @param reader Reader or buffer to decode from
            * @param [length] Message length if known beforehand
            * @returns Person
            * @throws {Error} If the payload is not a reader or valid buffer
            * @throws {$protobuf.util.ProtocolError} If required fields are missing
            */
            public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): Person;
    
            /**
            * Decodes a Person message from the specified reader or buffer, length delimited.
            * @param reader Reader or buffer to decode from
            * @returns Person
            * @throws {Error} If the payload is not a reader or valid buffer
            * @throws {$protobuf.util.ProtocolError} If required fields are missing
            */
            public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): Person;
    
            /**
            * Verifies a Person message.
            * @param message Plain object to verify
            * @returns `null` if valid, otherwise the reason why it is not
            */
            public static verify(message: { [k: string]: any }): (string|null);
    
            /**
            * Creates a Person message from a plain object. Also converts values to their respective internal types.
            * @param object Plain object
            * @returns Person
            */
            public static fromObject(object: { [k: string]: any }): Person;
    
            /**
            * Creates a plain object from a Person message. Also converts values to other types if specified.
            * @param message Person
            * @param [options] Conversion options
            * @returns Plain object
            */
            public static toObject(message: Person, options?: $protobuf.IConversionOptions): { [k: string]: any };
    
            /**
            * Converts this Person to JSON.
            * @returns JSON object
            */
            public toJSON(): { [k: string]: any };
        }
    
        export namespace Person {
    
            /** DeviceType enum. */
            enum DeviceType {
                iOS = 0,
                Android = 1
            }
        }
    複製代碼
  13. 範型
    • 什麼是泛型 咱們能夠理解爲泛型就是在編譯期間不肯定方法的類型(普遍之意思),在方法調用時,由程序員指定泛型具體指向什麼類型。泛型在傳統面向對象編程語言中是極爲常見的,ts中固然也執行泛型,若是你理解c#或java中的泛型,相信本篇理解起來會很容易
    • 例子
    // 範型函數
        function getMin<T> (arr: T[]) :T {
            let min = arr[0];
            arr.forEach((value): void => {
                if(value < min) {
                    min = value;
                }
            });
            return min;
        }
        //2 泛型類
        class GetMin<T> {
            arr: T[] = [];
            add( ele: T ) {
                this.arr.push(ele);
            }
            min(): T {
                var min = this.arr[0];
                this.arr.forEach(function (value) {
                    if(value < min) {
                        min = value;
                    }
                });
                return min;
            }
        }
        var gm1 = new GetMin<number>();
        gm1.add(5);
        gm1.add(3);
        gm1.add(2);
        gm1.add(9);
        console.log(gm1.min());
        
        var gm2= new GetMin<string>();
        gm2.add("tom");
        gm2.add("jerry");
        gm2.add("jack");
        gm2.add("sunny");
        console.log(gm2.min());
    
        /** * 3 泛型函數接口 */
        interface ConfigFn<T>{
            (value: T): T;
        }
        
        var getData: ConfigFn = function<T> (value: T): T {
            return value;
        }
        getData<string>('張三');
        // getData<string>(1243); //錯誤
        
        
        // 相似 Map<String,Object> Param 接口 這種忘了什麼意思了
        interface Param {
            [index:string]:any
        }
        //4 泛型類接口
        class User{
            id: number;//id主鍵自增
            name: string;//姓名
            sex: number;//性別 1男 2女
            age: number;//年齡
            city: string;//城市
            describe: string;//描述
        
        }
        
        //泛型接口
        interface  BaseDao<T> {
            findById(id: number): T;//根據主鍵id查詢一個實體
            findPageList(param: Param): T[];//查詢分頁列表
            findPageCount(param: Param): number;//查詢分頁count
            save(o: T): void;//保存一個實體
            update(o: T): void;//更新一個實體
            deleteById(id: number);//刪除一個實體
        }
        
        /** * 接口實現類 */
        class UserDao<T> implements BaseDao<T>{
            public userList: T[] = [];
            findById(id: number): T{
                let _length: number = this.userList.length;
                for (let i : number = 0; i < _length; i ++) {
                    let item: T = this.userList[i];
                    if (item.id == id) {
                        return item;
                    }
                }
                return null;
            }
            getUserListCount(): number {
                return this.userList.length;
            }
            save(o: T): void {
                this.userList.push(o);
            }
            update(o: T): void {
        
            }
            deleteById(id: number) {
        
            }
        }
    
        class Demo {
            constructor () {
                this.main();
            }   
            private main () : void {
                let users: UserDao<User> = new UserDao<User>();
                let curUser = new User();
                curUser.id = 12;
                curUser.name = 'lacy';
                users.save(curUser);
            }
        }
    複製代碼
相關文章
相關標籤/搜索