惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
The Blog of Author Tim Ferriss
Know Your Adversary
Know Your Adversary
P
Palo Alto Networks Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
K
Kaspersky official blog
L
LINUX DO - 热门话题
P
Proofpoint News Feed
P
Privacy & Cybersecurity Law Blog
Google DeepMind News
Google DeepMind News
Attack and Defense Labs
Attack and Defense Labs
Cisco Talos Blog
Cisco Talos Blog
AI
AI
L
LINUX DO - 最新话题
H
Heimdal Security Blog
Hacker News: Ask HN
Hacker News: Ask HN
Webroot Blog
Webroot Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
The GitHub Blog
The GitHub Blog
I
Intezer
Blog — PlanetScale
Blog — PlanetScale
有赞技术团队
有赞技术团队
S
Securelist
博客园_首页
IT之家
IT之家
Schneier on Security
Schneier on Security
博客园 - 叶小钗
罗磊的独立博客
WordPress大学
WordPress大学
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
MongoDB | Blog
MongoDB | Blog
P
Proofpoint News Feed
阮一峰的网络日志
阮一峰的网络日志
A
Arctic Wolf
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
W
WeLiveSecurity
The Register - Security
The Register - Security
D
DataBreaches.Net
S
Security @ Cisco Blogs
Security Archives - TechRepublic
Security Archives - TechRepublic
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
腾讯CDC
Recorded Future
Recorded Future
NISL@THU
NISL@THU
N
News and Events Feed by Topic
T
Tailwind CSS Blog
N
News and Events Feed by Topic
Cyberwarzone
Cyberwarzone
T
Tor Project blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com

博客园 - 果然如此

微信小程序UI组件、开发框架、实用库 sql查询优化--数字转换字符串字段 Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad Git简易的命令行入门教程 .NET Framework 历史版本(2017年) 深入理解 JavaScript 事件循环(一)— event loop spring boot maven多模块打包部署到tomcat TypeScript白鹭引擎Egret防止按钮事件冒泡穿透 maven多模块启动required a bean of type com.xxx.xxx.service that could not be found. idea常用快捷键 启动类加注解@MapperScan spring boot mybatis 启动错误 Maven项目mybatis Invalid bound statement (not found)解决方法 Re:从零开始的Spring Security Oauth2(三) Re:从零开始的Spring Security Oauth2(二) Re:从零开始的Spring Security Oauth2(一) typescript多维对象数组仿List泛型 idea新建maven项目没有src目录 spring boot 错误:Check your ViewResolver setup 《乔布斯传》经典摘录(七)
TypeScript 基本语法
果然如此 · 2018-03-24 · via 博客园 - 果然如此

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

Any

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

Void

//空白
function warnUser(): void 

2.类

基本语法

class Animal {
    animalName:string;

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

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

var tom = new Animal("Tom");
tom.sayHello();

继承

class Animal {
    animalName:string;

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

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

class Cat extends Animal {
    

修饰符

当我们把animalName 改为private

class Animal {
    private animalName:string;

get,set 访问器

class Animal {
    private _animalName:string;

静态属性

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

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

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(); 

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");

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

泛型类约束

class 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 { }
}

合并模块和类

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