导语:TypeScript(如下简称TS) 是由微软开发的编程语言,是JavaScript的超集,于2013年10月发布第一个正式版0.9。最早代码托管在Codeplex,2014年7月移到了Github。它的代码风格和C#很像,这是由于TS是由C#首席架构师设计并主导开发的。javascript
编辑器首选MS自家开发的VS Code (推荐)。固然,Webstorm在2016年2月推出的版本内置了TS编译器,atom 须要安装 atom-typescript包,sublime须要安装Typescript-sublime-plugin。java
TS程序以.ts扩展名结尾。运行TS程序很简单,只须要安装编译器TS compile便可,须要经过npm 的方式安装它。webpack
npm install typescript -g
复制代码
安装完后,在全局会有tsc命令,须要经过它编译TS程序web
tsc hello.ts
复制代码
谈到TS,你们印象最深入的仍是TS的静态强类型了。虽然JS异常灵活,可是在大型复杂的web工程里面并不合适。除了TS,其它公司好比FB推出了Flow,Google推出了Clojure,这些都是为了给JS增长类型。typescript
概念:注解是一种轻量级的为函数或变量添加约束的方式。 语法:变量或者函数后接 :TypeAnnotationexpress
好比:npm
let a: number = 123;
function add(a: number, b: number): number {
return a + b;
}
复制代码
TS里的原始类型包括string, number和boolean,这些也是JS的原始类型。在TS里,你能够显示声明变量为某一种类型。编程
let num: number;
let str: string;
let bool: boolean;
num = 123;
num = 123.456;
num = '123'; // 错误
str = '123';
str = 123; // 错误
bool = true;
bool = false;
bool = 'false'; // 错误
复制代码
TS里手动指明一个数组类型很简单,只须要在普通类型注解后面加上[]符号。好比声明一个布尔数组为 :boolean[]json
let boolArray: boolean[];
boolArray = [true, false];
console.log(boolArray[0]); // true
console.log(boolArray.length); // 2
boolArray[1] = true;
boolArray = [false, false];
boolArray[0] = 'false'; // 错误
boolArray = 'false'; // 错误
boolArray = [true, 'false']; // 错误
复制代码
枚举在TS里面是原生支持的,使用枚举咱们能够定义一些带名字的常量,它的好处是可让语意更清晰。定义一个枚举值,须要使用 enum。数组
TS 仅支持基于数字的和字符串的枚举。若是是数字枚举,枚举值默认是从0开始,依次自增的。你也能够手动的设置第一个枚举值,好比为1。
enum Color {
RED = 1,
GREEN,
YELLOW
}
console.log(Color.GREEN); // 2
enum Direction {
UP = 'UP',
DOWN = 'DOWN',
LEFT = 'LEFT',
RIGHT = 'RIGHT'
}
console.log(Direction.UP); // 'UP'
复制代码
虽然TS支持异构枚举(即数字和字符串混搭的枚举),可是并不建议使用这种方式。
和其它语言(好比C++, java)不一样的是,TS 里接口能够描述变量、函数类型和类类型,其它语言只能描述类类型。另外,TS中的接口描述变量时可使用?定义某个变量为可选变量。好比对某个对象进行约束时,若是对象的某个属性设置成了可选,则传入的对象能够不包含这个属性。
interface LabelledValue {
size?: Number,
label: String
}
function printLabel(labelObject: LabelledValue) {
return labelObject.label;
}
// 因为size设置成了可选变量,则传入的对象能够不包含size属性
console.log(printLabel({
label: 'size 1 object'
}));
复制代码
接口出了能够用来约束JS对象以外,也能够用来约束函数类型。好比:
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function(src: string, sub: string): boolean {
let result = src.search(sub);
return result > -1;
}
复制代码
说明:对于函数类型的类型检查来讲,函数的参数名不须要与接口里定义的名字相匹配。
与C#或Java里接口的基本做用同样,TypeScript也可以用它来明确的强制一个类去符合某种契约。不一样的是,C#或Java里面的接口描述类类型时,只能定义函数,TS里则还能够定义属性。若是某个类继承了这个接口,那么这个类必须包含接口里定义的属性和方法。
interface ClockInterface {
currentTime: Date;
setTime(d: Date): any;
}
class Clock implements ClockInterface {
currentTime = new Date();
setTime(d: Date) {
this.currentTime = d;
}
constructor(h: number, m: number) { }
}
复制代码
设计的出发点:可重用性。组件不只可以支持当前的数据类型,同时也能支持将来的数据类型。
好比咱们须要一个函数,同时支持入参是一个数字或字符串,返回值的类型和参数类型相同:
function identity(arg: number): number {
return arg;
}
function identity(arg: string): string {
return arg;
}
复制代码
这个时候就须要引入泛型去解决这个问题了。在TS里,泛型的类型变量定义为T,须要使用<>包裹起来,这个时候函数会捕获入参的类型,而后在后面就可使用这个类型了。以下:。
function identity<T>(arg: T): T {
return arg;
}
let output1 = identity<string>("myString"); // myString
let output2 = identity("myString"); // myString
复制代码
因为TS的类型推断,调用时不须要显示的指明类型,推荐使用上面代码中的第二种方式。
定义:经过 abstract 来修饰的类称为抽象类。
特色:
值得一提的是:抽象类和接口在描述类类型时,虽然比较相似。可是抽象类只能继承一个抽象类或者一个接口,而接口能够多重继承。
Decorator是一个函数,用来修饰类、属性、方法和参数。使用 @expression 语。
Decorator 的改变是在编译期改变,而不是运行期。装饰器包括多个规范,TC39在stage-0 和 stage-2分别定了修饰属性、方法的规范和修饰类的规范。
@func 修饰 类A 等价于 A = func(A),至关于把旧class转换成了新的class。能够理解为一个加工函数,它接受一个类,加工后返回另外一个类。
@testable
class MyTestableClass {
// ...
}
function testable(target) {
target.isTestable = true;
return target;
}
function getMetaData(target) {
return target.isTestable;
}
console.log(getMetaData(MyTestableClass)) // true
复制代码
装饰器除了修饰类以外,也能够用来修饰方法:
class A {
@func()
static method() {
}
}
function func() {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
console.log('func 被调用了');
};
}
A.method();
复制代码
@func 修饰 类A 上的 方法 method 是借助 Object 基类上的 defineProperty来实现的。原理以下:
const oldDescriptor = Object.getOwnPropertyDescriptor(A.property, 'method');
const newDescriptor = func(A.property, 'method', 'oldDescriptor');
Object.defineProperty(A.property, 'method', newDescriptor);
复制代码
tsconfig.json是TS项目的配置文件,能够描述整个工程的编译参数。
初始化一个 tsconfig.json 命令:
$ tsc --init
复制代码
tsconfig.json里面的经常使用字段解释以下:
要想在webpack里面使用TS,只需两步。第一,安装ts-loader;第二,设置webpack配置中的resolve.extension 包含 .ts 和 .tsx。
下面是一个最简单的配置:
// webpack.config.js
module.exports = {
entry: "./src/index.ts",
output: {
filename: "./dist/bundle.js",
},
resolve: {
extensions: ['.ts', '.js', '.json']
},
devtool: "source-map",
module: {
rules: [{
test: /\.tsx?$/,
loader: 'ts-loader'
}]
},
};
复制代码
整体而言,TS相比ES6 + babel,包含如下优点: