1. TypeScript简介 TypeScript是JavaScript的超集,添加了类型系统和对ES6+特性的支持,由Microsoft开发和维护。它可以编译成纯JavaScript,在任何浏览器、任何操作系统上运行。
1.1 TypeScript的优势
静态类型检查 :在编译时发现错误,而不是在运行时
更好的IDE支持 :代码补全、接口提示、跳转到定义等
更易于维护 :类型系统使代码更加自文档化
更好的团队协作 :明确的接口定义使协作更加顺畅
2. 基础类型 2.1 基本类型注解 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 let isDone : boolean = false ;let decimal : number = 6 ;let hex : number = 0xf00d ;let binary : number = 0b1010 ;let octal : number = 0o744 ;let color : string = "blue" ;let sentence : string = `The color is ${color} ` ;let list : number [] = [1 , 2 , 3 ];let list2 : Array <number > = [1 , 2 , 3 ]; let x : [string , number ] = ["hello" , 10 ];enum Color {Red , Green , Blue }let c : Color = Color .Green ;let notSure : any = 4 ;notSure = "maybe a string" ; notSure = false ; function warnUser ( ): void { console .log ("This is a warning message" ); } let u : undefined = undefined ;let n : null = null ;function error (message: string ): never { throw new Error (message); }
2.2 类型断言 1 2 3 4 5 6 7 let someValue : any = "this is a string" ;let strLength : number = (<string >someValue).length ;let strLength2 : number = (someValue as string ).length ;
3. 接口 接口是TypeScript的核心特性之一,用于定义对象的形状。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 interface User { name : string ; id : number ; email?: string ; readonly createdAt : Date ; } function createUser (user: User ): User { return user; } let user = createUser ({ name : "张三" , id : 1 , createdAt : new Date () });
3.1 函数类型接口 1 2 3 4 5 6 7 interface SearchFunc { (source : string , subString : string ): boolean ; } let mySearch : SearchFunc = function (src, sub ) { return src.search (sub) > -1 ; };
3.2 可索引类型 1 2 3 4 5 6 interface StringArray { [index : number ]: string ; } let myArray : StringArray = ["Bob" , "Fred" ];let myStr : string = myArray[0 ];
4.类 TypeScript支持基于类的面向对象编程特性。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 class Person { private name : string ; protected age : number ; constructor (name: string , age: number ) { this .name = name; this .age = age; } greet (): string { return `Hello, my name is ${this .name} and I am ${this .age} years old` ; } } class Employee extends Person { private department : string ; constructor (name: string , age: number , department: string ) { super (name, age); this .department = department; } introduce (): string { return `${super .greet()} and I work in ${this .department} ` ; } } let howard = new Employee ("Howard" , 42 , "Sales" );console .log (howard.introduce ());
5.泛型 泛型允许创建可重用的组件,一个组件可以支持多种类型的数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 function identity<T>(arg : T): T { return arg; } let output1 = identity<string >("myString" );let output2 = identity ("myString" );interface GenericIdentityFn <T> { (arg : T): T; } class GenericNumber <T> { zeroValue : T; add : (x: T, y: T ) => T; }
6.高级类型 6.1 联合类型 1 2 3 function padLeft (value: string , padding: string | number ) { }
6.2 交叉类型 1 2 3 4 5 6 7 8 9 10 interface ErrorHandling { success : boolean ; error?: { message : string }; } interface ArtworksData { artworks : { title : string }[]; } type ArtworksResponse = ArtworksData & ErrorHandling ;
6.3 类型别名 1 2 3 type Name = string ;type NameResolver = () => string ;type NameOrResolver = Name | NameResolver ;
7.实用技巧 7.1 严格空值检查 1 2 3 4 5 6 7 8 9 10 let s = "foo" ;s = null ; let sn : string | null = "bar" ;sn = null ; function f (x?: number ) { }
7.2 非空断言操作符 1 2 3 4 function validateEntity (e?: Entity ) { console .log (e!.name ); }
8.配置文件 一个基本的tsconfig.json配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 { "compilerOptions" : { "target" : "es5" , "module" : "commonjs" , "strict" : true , "esModuleInterop" : true , "skipLibCheck" : true , "forceConsistentCasingInFileNames" : true , "outDir" : "./dist" } , "include" : [ "src/**/*" ] , "exclude" : [ "node_modules" , "**/*.spec.ts" ] }