• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript基本语法TypeScript基本语法

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
 

TypeScript 是微软开发的 JavaScript 的超集,TypeScript兼容JavaScript,可以载入JavaScript代码然后运行。TypeScript与JavaScript相比进步的地方 包括:加入注释,让编译器理解所支持的对象和函数,编译器会移除注释,不会增加开销;增加一个完整的类结构,使之更新是传统的面向对象语言。

TypeScript 微软官方网站 http://www.typescriptlang.org/
TypeScript 源码 http://typescript.codeplex.com

1.基本数据类型

Boolean

//Boolean
var isDone:boolean = false;

Number

//Number
var width:number = 100;

String

//String
var name:string = "hello";

Array

//Array
var list:number[] = [1, 2, 3];
var list:Array<number>=[1, 2, 3];

Enum

//Enum
enum Color {Red, Green, Blue}
var c: Color = Color.Red;
alert(c);//默认下标从0开始,alert(0);
//可以手动指定下标
enum Color1 {Red = 1, Green, Blue}
var c1: Color1 = Color1.Green;
alert(c1);//alert(2)
//根据下标查找名称
enum Color2 {Red = 1, Green=2, Blue=4}
var c2: string = Color2[4];
alert(c2);//alert(Blue)

Any

//不确定类型,退出编译检查
var notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

//不确定数组元素类型
var anylist:any[] = [1, true, "free"];
anylist[1] = 100;

Void

//空白
function warnUser(): void {
    alert(123);
}

2.类

基本语法

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)

修饰符

当我们把animalName 改为private

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)

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("年龄")

6.泛型

基本语法

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>) {
    // ...
}

7.合并

合并接口

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;
        }
    }
}

不能合并

  • 类与类不能合并
  • 接口与类不能合并
  • 变量与类不能合并

转载请注明出处:http://www.cnblogs.com/xcong/p/4570235.html
文中代码引用自Ts官网和极客学院
TS文件下载 https://files.cnblogs.com/files/xcong/TsDemo.zip

TypeScript 是微软开发的 JavaScript 的超集,TypeScript兼容JavaScript,可以载入JavaScript代码然后运行。TypeScript与JavaScript相比进步的地方 包括:加入注释,让编译器理解所支持的对象和函数,编译器会移除注释,不会增加开销;增加一个完整的类结构,使之更新是传统的面向对象语言。

TypeScript 微软官方网站 http://www.typescriptlang.org/
TypeScript 源码 http://typescript.codeplex.com

1.基本数据类型

Boolean

//Boolean
var isDone:boolean = false;

Number

//Number
var width:number = 100;

String

//String
var name:string = "hello";

Array

//Array
var list:number[] = [1, 2, 3];
var list:Array<number>=[1, 2, 3];

Enum

//Enum
enum Color {Red, Green, Blue}
var c: Color = Color.Red;
alert(c);//默认下标从0开始,alert(0);
//可以手动指定下标
enum Color1 {Red = 1, Green, Blue}
var c1: Color1 = Color1.Green;
alert(c1);//alert(2)
//根据下标查找名称
enum Color2 {Red = 1, Green=2, Blue=4}
var c2: string = Color2[4];
alert(c2);//alert(Blue)

Any

//不确定类型,退出编译检查
var notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

//不确定数组元素类型
var anylist:any[] = [1, true, "free"];
anylist[1] = 100;

Void

//空白
function warnUser(): void {
    alert(123);
}

2.类

基本语法

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)

修饰符

当我们把animalName 改为private

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)

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("年龄")

6.泛型

基本语法

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>) {
    // ...
}

7.合并

合并接口

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;
        }
    }
}

不能合并

  • 类与类不能合并
  • 接口与类不能合并
  • 变量与类不能合并

转载请注明出处:http://www.cnblogs.com/xcong/p/4570235.html
文中代码引用自Ts官网和极客学院
TS文件下载 https://files.cnblogs.com/files/xcong/TsDemo.zip


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScriptHandbook1——基本类型(翻译)发布时间:2022-07-18
下一篇:
TypeScript学习一参数,函数,析构表达式发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap