- 基礎數據類型
- 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)
Console.log(Color[0])
複製代碼
- void
function hello(): void {
alert("Hello Runoob");
}
複製代碼
- null
複製代碼
- undefined
複製代碼
- never
let x: never;
let y: number;
x = (()=>{ throw new Error('exception')})(); // 運行正確,never 類型能夠賦值給 數字類型 y = (()=>{ throw new Error('exception')})(); 複製代碼
- any
let a: any;
a = 12;
a = "asdasd";
a = true;
複製代碼
- TypeScript 變量聲明
- TypeScript 變量的命名規則:
- 變量名稱能夠包含數字和字母
- 除了下劃線 _ 和美圓 $ 符號外,不能包含其餘特殊字符,包括空格。
- 變量名不能以數字開頭。
- 變量的聲明
let [變量名] : [類型] = 值;
複製代碼
- 類型斷言
class TestClass {
public name: string = "12";
}
function test (a: number | string) :void {
let b: string = <string>a;
}
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
let c: string = <number><any>a;
let d: string = <number><unknown>a;
enum AllNum {
hp_min = 0,
marrid_age = 18
}
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);
}
}
複製代碼
- TypeScript 運算符 不講都同樣。
- TypeScript 條件語句 跟js的都是同樣的。
- TypeScript 循環
let _length: number = 12;
for (let i : number; i < _length; i ++) {
console.log(i);
}
複製代碼
- TypeScript 函數
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);
}
test("11");
test("11", 12, true, "a", "d")
複製代碼
- TypeScript 聯合類型 能夠經過管道(|)將變量設置多種類型,賦值時能夠根據設置的類型來賦值
let a: string | number;
a = "12";
a = 12;
let a: string[] | number[];
let b: (string | number)[];
a = [1, "12"];
b = [1, "12"];
複製代碼
- TypeScript 接口 接口是一系列抽象方法的聲明,是一些方法特徵的集合,這些方法都應該是抽象的,須要由具體的類去實現 通常用來定義數據結構,或者指定方法須要具備哪些API
interface interface_name {
}
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 {}
}
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);
}
}
複製代碼
- 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;
}
}
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 {
}
}
複製代碼
- 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();
複製代碼
- TypeScript 模塊
export interface IShape {
draw();
}
import shape = require("./IShape");
export class Circle implements shape.IShape {
public draw() {
console.log("Cirlce is drawn (external module)");
}
}
複製代碼
- 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
}
}
複製代碼
- 範型
- 什麼是泛型 咱們能夠理解爲泛型就是在編譯期間不肯定方法的類型(普遍之意思),在方法調用時,由程序員指定泛型具體指向什麼類型。泛型在傳統面向對象編程語言中是極爲常見的,ts中固然也執行泛型,若是你理解c#或java中的泛型,相信本篇理解起來會很容易
- 例子
function getMin<T> (arr: T[]) :T {
let min = arr[0];
arr.forEach((value): void => {
if(value < min) {
min = value;
}
});
return min;
}
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());
interface ConfigFn<T>{
(value: T): T;
}
var getData: ConfigFn = function<T> (value: T): T {
return value;
}
getData<string>('張三');
interface Param {
[index:string]:any
}
class User{
id: number;
name: string;
sex: number;
age: number;
city: string;
describe: string;
}
interface BaseDao<T> {
findById(id: number): T;
findPageList(param: Param): T[];
findPageCount(param: Param): number;
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);
}
}
複製代碼