前端javascript的编程思想与后端java面向对象的编程思想有很大的不一样,微软公司借鉴了coffeescript语言,继承了不少C#和java的编程思想,推出了TypeScript。期间随着js的升级换代出了ES6,微软的TypeScript不只吸取了ES6的新特性,还能够编译成ES6的样子,所以在TypeScript里直接写ES6的js是基本没什么问题的。相对于javascript的宽松自由,它添加了更多的约束和规则,是之后javascript发展的主要趋势。
TypeScript和ES6,ES5的关系以下:javascript
1. 安装:html
npm install -g typescript
查看TypeScript版本:前端
tsc -v
如今不少文本编辑器和IDE都自己支持或经过插件支持TypeScript语法、智能提示、纠错。java
2. 编译:node
TypeScript是写在.ts文件里的,不能直接在浏览器上运行,须要编译成js文件后运行。通常有如下几种方式编译:jquery
(1) 经过命令行工具tsc webpack
如tsc main.ts,也能够列出全部的文件或者使用通配符来一次编译多个文件,如:git
//构建main.ts和worker.ts tsc main.ts worker.ts //构建全部ts文件 tsc *.ts
(2) 添加配置文件tsconfig.json,包含多种构建设置,从而实现自动化进程 github
{ "compilerOptions": { "target": "es5", //指定生成代码的兼容版本 "importHelpers": true, "lib": [ "es2016", "dom" ], "moduleResolution": "node", //指定模块的解析策略,Node或者是classic,默认是classic。 "emitDecoratorMetadata": true, //设置为true,则使用元数据特性 "experimentalDecorators": true, //设置为true,则支持ES7的装饰器特性 "strictNullChecks": true, "alwaysStrict": true, "noImplicitAny": false, //当表达式和申明类型为any时,是否须要发出警告,设置true,则不警告 "noUnusedLocals": true, "baseUrl": "", "paths": { "@schenker/foundation": ["portal/nges-portal-web/src/main/resources/webapp/js/portal-framework"], "@schenker/eservice-portal-entry": ["eservices/portal-entry/eservices-portal-entry-web/src/main/resources/webapp/js/portal-entry/eservice.ts"], "@schenker/eservice-booking": ["eservices/booking/eservices-booking-web/src/main/resources/webapp/js/booking/eservice.ts"], "@schenker/eservice-sla-reporting": ["eservices/sla-reporting/eservices-sla-reporting-web/src/main/resources/webapp/js/sla-reporting/eservice.ts"] }, //typeRoots和types选项指定了node_modules/@types下的jasmine,angular等包括在内,其他的type不适用 "typeRoots": ["node_modules/@types"], "types": [ "jasmine", "angular", "node", "webpack", "webpack-env", "spin.js", "jquery", "moment", "angular-mocks" ] }, //用于排除不须要编译的ts文件。该属性和files属性冲突。二者只能设置其一。 "exclude": [ "node_modules/*" ], "angularCompilerOptions": { "preserveWhitespaces": false } }
更多配置选项能够查看TypeScript官方文档: https://www.typescriptlang.org/docs/handbook/tsconfig-json.htmlweb
具体配置解析也能够看:https://github.com/hstarorg/HstarDoc/blob/master/%E5%89%8D%E7%AB%AF%E7%9B%B8%E5%85%B3/TypeScript%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6tsconfig%E7%AE%80%E6%9E%90.md
(3) 使用自动化构建工具,如gulp或webpack
TypeScript基本语法
boolean
let isDone: boolean = false;
number: 全部数字都是数值类型的,不管是整数、浮点型或者其余数值类型都相同。
let height: number = 6;
string
let name1: string = 'tom';
array
let list:number[] = [1, 2, 3];
let list1:Array<number> = [1, 2, 3];
enum
enum Color {Red, Green, Blue} let c: Color = Color.Green; console.log(c); // 获取值,至关于 console.log(Color["Green"]); enum Color1 {Red = 1, Green = 2, Blue = 4} let c1: Color1 = Color1.Green; console.log(c1); // 获取值,2
any: any能够是任意对象,会根据须要改变数据类型
let anylist:any[] = [1, true, "free"]; anylist[2] = 100;
void: 不返回值
function warnUser(): void { console.log("This is my warning message"); } warnUser();
2.接口
为何须要接口呢,能够看如下一段代码:
function calculateResult({x=0, y=0}:{x:number, y:number}){ //calculate method } function calculateResult2({x=0, y=0, z=0}:{x:number, y:number, z:number}){ //calculate method }
若是有不少个参数须要进行计算的话,那么咱们须要不断复制增长参数,整个代码会很是臃肿,可是有了接口以后,会很是方便。如:
function calculateResult({x=0, y=0}:pointer2d){ //calculate method } function calculateResult2({x=0, y=0, z=0}:pointer3d){ //calculate method } interface pointer2d { x: number; y: number; } interface pointer3d extends pointer2d { z: number; }
接口的做用就是去描述结构的形态。
接口一般会根据一个对象是否符合某种特定结构来进行类型检查。经过定义一个接口咱们能够命名一个特殊的组合变量,确保它们会一直一块儿运行。
interface LabelledValue { label: string; } function printLabel(labelledObj: LabelledValue) { console.log(labelledObj.label); } var myObj = {label: "only label"}; var myObj1 = {size: 10, label: "Size 10 Object"}; // # 接口是鸭子类型, 只要是有label的对象均可以传进去 printLabel(myObj); printLabel(myObj1);
接口还有其余一些玩法,如:
(1)可选属性
interface SquareConfig { color?: string; // 用?来表示可选属性 width?: number; } function createSquare(config: SquareConfig): {color: string; area: number} { var newSquare = {color: "white", area: 100}; if (config.color) { newSquare.color = config.color; } if (config.width) { newSquare.area = config.width * config.width; } return newSquare; } var mySquare = createSquare({color: "black"}); var mySquare1 = createSquare({width: 20}); console.log(mySquare); console.log(mySquare1);
(2)函数类型
interface SearchFunc { (source: string, subString: string): boolean; // 表示一个接受2个string参数, 返回bool的函数 } var mySearch: SearchFunc; mySearch = function(source: string, subString: string): boolean { var result = source.search(subString); if (result == -1) { return false; } else { return true; } }; var result: boolean = mySearch("test", "te"); console.log(result);
(3)数组类型
interface StringArray { [index: number]: string; // 表示string数组 } var myArray: StringArray; myArray = ["Bob", "Fred"]; console.log(myArray["0"]); console.log(myArray["1"]);
(4)类类型
interface ClockStatic { new (hour: number, minute: number); } // # 这里会报错. 由于只有实例部分才检查, 而构造函数是静态部分 //class Clock implements ClockStatic { // currentTime: Date; // constructor(h: number, m: number) { } //} class Clock { currentTime: Date; constructor(h: number, m: number) { } } // # 这里须要注意 // # 咱们直接使用class,这样就会检查签名 var cs: ClockStatic = Clock; var newClock: ClockStatic = new cs(7, 30); console.log(newClock);
(5)继承接口
interface Shape { color: string; } interface PenStroke { penWidth: number; } interface Square extends Shape, PenStroke { // 使用extends继承接口 sideLength: number; } var square = <Square>{}; square.color = "blue"; square.sideLength = 10; square.penWidth = 5.0;
未待完续.........