TypeScript

TypeScript是JS的超集,它可以编译成普通的JavaScript代码。

TypeScript通过类型注解提供编译时的静态类型检查。

官网:http://www.typescriptlang.org/

TypeScript 主要特点包括:
  TypeScript 兼容 ECMAScript 2015(ES6)规范

  更好的支持OOP。

  •   类 Classes
  •   接口 Interfaces
  •   模块 Modules 
  •   类型注解 Type annotations
  •   编译时类型检查 Compile time type checking 

 

TypeScript_第1张图片

上面的可能用不成,你懂的:

npm install -g cnpm --registry=https://registry.npm.taobao.org
cnpm install

添加watch,改变TS内容后,自动编译。tsc -w xxx.ts

默认编译为ES3,我这里使用:tsc -w -t es6 index.ts

 

搭建VSCode开发环境

//package.json

{
  "name": "typescript.demo",
  "version": "1.0.0",
  "private": true,
  "main": "index.html",
  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },
  "license": "ISC",
  "dependencies": {
    "bootstrap": "^3.3.6"
  },
  "devDependencies": {
    "concurrently": "^2.2.0",
    "lite-server": "^2.2.2",
    "typescript": "^2.0.2",
    "typings":"^1.3.2"
  }
}
//tsconfig.json

{
    "compileOnSave": true,
    "compilerOptions": {
        "target": "es6",
        "noImplicitAny": true,  
        "removeComments": true,
        "preserveConstEnums": true,   
        "sourceMap": true
    }
    // "include": [
    //     "src/**/*"
    // ],
    // "exclude": [
    //     "node_modules",
    // ]
}

 

基础类型

在TS中,声明类型叫法比较诡异,叫类型注解,算了,随它吧。类型注解在TypeScript中是记录函数或变量约束的简便方法

let isDone: boolean = false;

let n: number = 1;

let str: string = "hello";

 

Array:

let list: number[] = [1,2,3];

let list: Array = [1,2,3];

 

元组:

let x: [string,number];

x = ['hello',10];

访问:x[0]

 

Enum:

enum Color {red,green,blue};

let c: Color = Color.green;

//指定起始index
enum Color {red=1,Green,Blue};

//根据index取得value
let colorName: string = Color[1];

 

const enum(完全嵌入的枚举)

const enum声明与正常的enum在类型安全方面具有同样的作用,只是在编译时会将枚举变量所代表的数字值直接替换到对应位置上。 

 

const enum Color{
  Red,
  Green,
  Blue,
  GreenAndBlueSum = Green | Blue
}

let r = Color.Red;
console.log(r);
let s = Color.GreenAndBlueSum;  
console.log(s);

 

Any:

let v: any = 10;

let list: any[] = [1,true,"aaa"];

 

Void:

function varnUser():void{
  alert("aaa");
} 

 

类型断言

//第一种
let someValue: any = "this is a string";
let strLength: number = (someValue).length;

//第二种
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;

 

使用typeof或者instanceof来检查变量类型

if(typeof x ==='string'){}

if(pet instanceof Dog){}

 

const同let一样是块级作用域,一旦赋值后,不能重新赋值。

const num = 10;

 

解构数组

let [a,b] = [1,2];
let [a] = [1,2,3]; alert(a);

可以在数组里用...语法创建剩余变量:

let [first, ...rest] = [1, 2, 3, 4];
console.log(first); // outputs 1
console.log(rest); // outputs [ 2, 3, 4 ]

 

解构对象

let {a,b} = {a:"baz",b:101,c:2};    // ({ a, b } = { a: "baz", b: 101 });
alert(a);
let {a, ...others} = {a:"baz",b:101,c:2}; 
let n= others.b + others.c;

 

模块

从ECMAScript 2015开始,JavaScript引入了模块的概念。TypeScript也沿用这个概念。

模块是自声明的;两个模块之间的关系是通过在文件级别上使用imports和exports建立的。

模块使用模块加载器去导入其它的模块。 在运行时,模块加载器在执行此模块代码前去查找并执行这个模块的所有依赖。

export

任何声明(比如变量,函数,类或接口)都能够通过添加export关键字来导出。

//Validation.ts
export interface StringValidator {
    isAcceptable(s: string): boolean;
}
//ZipCodeValidator.ts
export const numberRegexp = /^[0-9]+$/;

export class ZipCodeValidator implements StringValidator {
    isAcceptable(s: string) {
        return s.length === 5 && numberRegexp.test(s);
    }
}

也可以这样单独写导出语句

export { ZipCodeValidator };
export { ZipCodeValidator as mainValidator };
export {ZipCodeValidator as RegExpBasedZipCodeValidator} from "./ZipCodeValidator";
export * from
"./ZipCodeValidator"; //导出模块中的所有子模块
 
   

 

import

import { ZipCodeValidator } from "./ZipCodeValidator";

let myValidator = new ZipCodeValidator();
//对导入内容重命名
import { ZipCodeValidator as ZCV } from "./ZipCodeValidator"; let myValidator = new ZCV();
//将整个模块导入到一个变量,并通过它来访问模块的导出部分
import * as validator from "./ZipCodeValidator";
let myValidator = new validator.ZipCodeValidator();

 

命名空间

任何使用module关键字来声明一个内部模块的地方都应该使用namespace关键字来替换。

namespace HelloWorld {
    export interface Person {
        SayHello(name:string):string;
    }

    export class Student implements Person {
        SayHello(s: string) {
            return "hello" + s;
        }
    }
}

HelloWorld.Student s = new HelloWorld.Student();
let str = s.SayHello("jay");
alert(str);

 

命名空间可嵌套

namespace Shapes {
    export namespace Polygons {
        export class Triangle { }
        export class Square { }
    }
}

import polygons = Shapes.Polygons;
let sq = new polygons.Square(); 

 

命名空间和模块比较

命名空间是位于全局命名空间下的一个普通的带有名字的JavaScript对象。你可以把所有依赖都放在HTML页面的 

你可能感兴趣的:(TypeScript)