TypeScript 基本语法

页面导航:首页 > 网络编程 > JavaScript > TypeScript 基本语法

TypeScript 基本语法

来源: 作者: 时间:2016-01-23 10:23 【

1 基本数据类型xinterface ICar { color:string;}class Bus implements ICar { color:string; constructor() { this color = Blue; }}var bus = new
1.基本数据类型
x
interface ICar {
    color:string;
}

class Bus implements ICar {
    color:string;
    constructor() {
        this.color = "Blue";
    }
}

var bus = new Bus();
alert(bus.color);
继承接口
//继承接口
interface Shape {
    color: string;
}

interface PenStroke {
    penWidth: number;
}

interface Square extends Shape, PenStroke {
    sideLength: number;
}
可选属性
interface ICar {
    color:string;
    safetyDevice?:any;//实现类无需实现
}

function MoveCar(car:ICar){
    if(car.safetyDevice)
    {
        alert("The car is safe");
    }
    else
    {
        alert("The car is not safe");
    }
}

 

2.类
基本语法
x
interface ICar {
    color:string;
}

class Bus implements ICar {
    color:string;
    constructor() {
        this.color = "Blue";
    }
}

var bus = new Bus();
alert(bus.color);
继承接口
//继承接口
interface Shape {
    color: string;
}

interface PenStroke {
    penWidth: number;
}

interface Square extends Shape, PenStroke {
    sideLength: number;
}
可选属性
interface ICar {
    color:string;
    safetyDevice?:any;//实现类无需实现
}

function MoveCar(car:ICar){
    if(car.safetyDevice)
    {
        alert("The car is safe");
    }
    else
    {
        alert("The car is not safe");
    }
}

 

3.接口
基本语法
interface ICar {
    color:string;
}

class Bus implements ICar {
    color:string;
    constructor() {
        this.color = "Blue";
    }
}

var bus = new Bus();
alert(bus.color);
继承接口
//继承接口
interface Shape {
    color: string;
}

interface PenStroke {
    penWidth: number;
}

interface Square extends Shape, PenStroke {
    sideLength: number;
}
可选属性
interface ICar {
    color:string;
    safetyDevice?:any;//实现类无需实现
}

function MoveCar(car:ICar){
    if(car.safetyDevice)
    {
        alert("The car is safe");
    }
    else
    {
        alert("The car is not safe");
    }
}

 

4.模块(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()'

 

5.函数(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("年龄")
5.泛型
基本语法
function identity<T>(arg: T): T {
    return arg;
}

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

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

var myIdentity:GenericIdentityFn = identity;
泛型类
class GenericNumber<T> {
    zeroValue:T;
    add:(x:T, y:T) => T;
}

var myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function (x, y) {
    return x + y;
};
泛型约束
interface Lengthwise {
    length: number;
}

function loggingIdentity<T extends Lengthwise>(arg:T):T {
    console.log(arg.length);
    return arg;
}

loggingIdentity(3);//error
loggingIdentity({length: 10, value: 3});  //只要类型包含length属性即可
泛型类约束
class Findable<T>
{
    //...
}
function find<T>(n: T, s: Findable<T>) {
    // ...
}

 

6.合并
合并接口
interface Box {
    height: number;
    width: number;
}

interface Box {
    scale: number;
}

var box: Box = {height: 5, width: 6, scale: 10};
合并模块
module Animals {
    exportclass Zebra { }
}

module Animals {
    exportinterface Legged { numberOfLegs: number; }
    exportclass Dog { }
}

//相当于
module Animals {
    exportinterface Legged { numberOfLegs: number; }
    
    exportclass Zebra { }
    exportclass Dog { }
}

 

合并模块和类
class Album {
    label:Album.AlbumLabel;
}
module Album {
    export class AlbumLabel {
    }
}

 

合并模块和函数
function buildLabel(name:string):string {
    return buildLabel.prefix + name + buildLabel.suffix;
}

module buildLabel {
    export var suffix = "";
    export var prefix = "Hello, ";
}

alert(buildLabel("Sam Smith"));

 

合并模块与枚举
enum Color {
    red = 1,
    green = 2,
    blue = 4
}

module Color {
    export function mixColor(colorName:string) {
        if (colorName == "yellow") {
            return Color.red + Color.green;
        }
        else if (colorName == "white") {
            return Color.red + Color.green + Color.blue;
        }
        else if (colorName == "magenta") {
            return Color.red + Color.blue;
        }
        else if (colorName == "cyan") {
            return Color.green + Color.blue;
        }
    }
}

 

不能合并
类与类不能合并
接口与类不能合并
变量与类不能合并
Tags:

文章评论

最 近 更 新
热 点 排 行
Js与CSS工具
代码转换工具

<