TypeScript 常用语法详解

本文参考链接:TypeScript 基本语法

1. 类
class Animal {
    animalName:string;

    constructor(name:string) {
        this.animalName = name;
    }

    sayHello() {
        alert(this.animalName + ": Hello");
    }
}

var tom = new Animal("Tom");
tom.sayHello();//alert(Tom:Hello)
 
  • 继承

 class Animal {
    animalName:string;

    constructor(name:string) {
        this.animalName = name;
    }

    sayHello() {
        alert(this.animalName + ": Hello");
    }
}

class Cat extends Animal {
    //重写sayHello方法
    sayHello() {
        alert(this.animalName + "(Cat):" + "Hello");
    }
}

class Mouse extends Animal {
    sayHello() {
        alert(this.animalName + "(Mouse):" + "Hello");
    }
}

var tom:Animal = new Cat("Tom");
tom.sayHello();//alert(Tom(Cat):Hello)
var jerry:Animal = new Mouse("Jerry");
jerry.sayHello();//alert(Jerry(Mouse):Hello)
  • 修饰符

 class Animal {
    private animalName:string;//默认是public

    constructor(name:string) {
        this.animalName = name;
    }
    //...
}

class Cat extends Animal {
    //重写sayHello方法
    sayHello() {
        alert(this.animalName + "(Cat):" + "Hello");//Error 编译不通过
    }
}
  • get,set 访问器

 class Animal {
    private _animalName:string;//默认是public

    get animalName():string {
        return this._animalName;
    }

    set animalName(name:string):string {
        this._animalName = name;
    }

    //...
}

  • 静态属性
//静态属性
class Table {
    static width = 100;
    static height = 200;
}

var width = Table.width;
alert(width);//alert(100)

 
2.模块(Modules)

作用:1.防止命名空间冲突;2.将一个功能模块很容易的划分到不同文件中,更容易维护;

  • 基本语法

 module MyDemo {
    export interface IDemo {

    }

    export class Demo implements IDemo {

    }
}
  • 别名
module Shapes {
    export module Polygons {
        export class Triangle { }
        export class Square { }
    }
}

import polygons = Shapes.Polygons;
var sq = new polygons.Square(); // 类似于 'new Shapes.Polygons.Square()'
 
3.函数(Function)

*基本语法

function add(x:number, y:number):number {
    return x + y;
}
// or
var myAdd = function (x:number, y:number):number {
    return x + y;
};
 
  • 完整的函数类型
var myAdd:(x:number, y:number)=>number =
    function (x:number, y:number):number {
        return x + y;
    };

为了增强可读性,给参数x、y具有实际的意义,可以这样写

var myAdd:(baseValue:number, increment:number)=>number =
    function (x:number, y:number):number {
        return x + y;
    };
 

第二部分number 是一个返回类型,如果无需返回类型,请使用 'void'
第三部分的function 参数类型,根据上下文类型进行推断,可以省略


 var myAdd:(baseValue:number, increment:number)=>number =
    function (x, y) {
        return x + y;
    };
  • 可选参数
//可选参数
function buildName(firstName:string, lastName?:string) {
    if (lastName)
        return firstName + " " + lastName;
    else return firstName;
}
var result1 = buildName("Bob");

 
  • 默认参数
//默认参数
function buildNameDefaultValue(firstName: string, lastName = "Smith") {
        return firstName + " " + lastName;
}
var result1 = buildNameDefaultValue("Bob");
 
  • 可变参数
    例如在C#中,方法参数定义使用param int[],调用方法时,就可以传递多个int类型的参数
    在TypeScript中

 
function buildNameRest(firstName:string, ...restOfName:string[]) {
    return firstName + " " + restOfName.join(" ");
}

var employeeName = buildNameRest("Joseph", "Samuel", "Lucas", "MacKinzie")
  • Lambads 和this关键字
var people={
    name:["张三","李四","王五","赵六"],
    getName:function(){
        return function(){
            var i=Math.floor(Math.random()*4);
            return {
                n:this.name[i]
            }
        }
    }
}

var pname=people.getName();
alert("名字:"+pname().n);
 

调用发现getName中的this关键字指向的是getName,访问不到外部的name属性
所以我们修改为:


 var people = {
    name: ["张三", "李四", "王五", "赵六"],
    getName: function () {
        return  ()=> {
            var i = Math.floor(Math.random() * 4);
            return {
                n: this.name[i]
            }
        }
    }
}

var pname = people.getName();
alert("名字:" + pname().n);
  • 重载
//重载
function student(name:string):string;
function student(age:number):number;
function student(numberorage:any):any {
    if (numberorage && typeof (numberorage) == "string")
        alert("姓名");
    else
        alert("年龄");
}
student("Tom");//alert("姓名")
student(15);//alert("年龄")
 
4.泛型
  • 基本语法
function identity(arg: T): T {
    return arg;
}

//数组泛型
function identity(arg: T[]): T[] {
    console.log(arg.length);
}
  • 泛型类型(通用的函数类型)
function identity(arg:T):T {
    return arg;
}
var myIdentity:(arg:T)=>T = identity;//T也可使用其他字母表示
//也可以这么写
//var myIdentity:{(arg:T): T} = identity;
  • 接口泛型

interface GenericIdentityFn {
    (arg:T): T;
}

function identity(arg:T):T {
    return arg;
}

var myIdentity:GenericIdentityFn = identity;
  • 泛型类

class GenericNumber {
    zeroValue:T;
    add:(x:T, y:T) => T;
}

var myGenericNumber = new GenericNumber();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function (x, y) {
    return x + y;
};

  • 泛型约束

interface Lengthwise {
    length: number;
}

function loggingIdentity(arg:T):T {
    console.log(arg.length);
    return arg;
}

loggingIdentity(3);//error
loggingIdentity({length: 10, value: 3});  //只要类型包含length属性即可
  • 泛型类约束

class Findable
{
    //...
}
function find(n: T, s: Findable) {
    // ...
}

你可能感兴趣的:(TypeScript 常用语法详解)