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);
            }
        }
    复制代码
相关文章
相关标签/搜索