TypeScript
一、TS简介
1、TypeScript是JavaScript类型的超集,它可以编译成纯JavaScript
2、TypeScript可以在任何浏览器、任何计算机和任何操作系统上运行,并且是开源的
1、编译typescript
npm安装:
1 npm install -g typescript
新建demo.ts文件
function test () { console.log('Hello TS') } test();
1 tsc demo.ts
2、运行typescript
1、运行js文件
1 node demo.js
2、运行ts文件
安装ts-node
1 npm i -g ts-node
运行ts文件(编译+运行)
1 ts-node demo.ts
二、TS变量声明
1 let num: number = 123;
2、字符串
1 let str: string = 'Hello TS'
3、
1 let isDone: boolean = true;
4、undefined和null
1 let a: undefined = undefined; 2 let b: null = null;
5、联合类型
1 let uniteType: "male" | "female"; 2 let c: boolean | string;
6、any(任意类型)
1 let d: any; 2 3 d = 123; 4 d = "Hello"
7、unknown(未知类型)
1、unknown实际上是一个类型安全的any
2、其他类型的变量,不能直接赋值给unknown
1 let _unknown: unknown; 2 _unknown = 123; 3 _unknown = true;
8、类型断言
1 // 写法一:尖括号 2 let someValue: any = "this is a string"; 3 let strLength: number = (<string>someValue).length; 4 5 // 写法二:as 6 let someValue: any = "this is a string"; 7 let strLength: number = (someValue as string).length;
9、void类型
1 // 没有返回值 2 function warnUser(): void { 3 console.log("This is my warning message"); 4 }
10、never类型
1 // 返回never的函数必须存在无法达到的终点 2 function error(message: string): never { 3 throw new Error(message); 4 } 5 6 // 推断的返回值类型为never 7 function fail() { 8 return error("Something failed"); 9 }
11、object类型
1 let obj: object; 2 let obj1: {}; 3 4 // 可选属性:age 5 let obj2: {name: string, age?: number}; 6 7 // name是必需属性,其他属性可选 8 let obj3: {name: string, [propName: string]: any}; 9 obj3 = {name: "张三", sex: "男"}
12、函数
1 let func: (a: number, b:number) => number 2 3 // 形参n1、n2可以不等于a、b 4 func = function(n1, n2){ 5 return n1 + n2; 6 }
函数声明
1 // function声明函数 2 function add(x: number, y: number): number { 3 return x + y; 4 } 5 6 // 匿名函数声明 7 let myAdd = function(x: number, y: number): number { 8 return x + y; 9 };
13、数组
1 // 写法一 2 let strArr: string[] = ["a", "b", "c"]; 3 let numArr: number[] = [1, 2, 3, 4, 5]; 4 5 // 写法二 6 let numArr1: Array<number> = [1, 2, 3, 4, 5];
14、元组
长度固定的数组
1 let x: [string, number]; 2 x = ['hello', 10]; // OK 3 x = [10, 'hello']; // Error
15、枚举
1 enum Gender{ 2 male, 3 female 4 } 5 6 let person: {name: string, gender: Gender}; 7 person = { 8 name: "张三", 9 gender: Gender.male 10 }; 11 12 // 判断性别 13 console.log(person.gender === Gender.male);
16、类型别名
1 type selectNum = 1 | 2 | 3 | 4 | 5; 2 let num: selectNum = 1; 3 4 type myType = { 5 name: string, 6 age: number 7 } 8 const obj: myType = { 9 name: "李四", 10 age: 20 11 }
三、TS配置文件
生成tsconfig.json
1 tsc -init
1 { 2 "compilerOptions": { 3 /* Visit https://aka.ms/tsconfig.json to read more about this file */ 4 5 /* Basic Options */ 6 // "incremental": true, /* Enable incremental compilation */ 7 "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */ 8 "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ 9 // "lib": [], /* Specify library files to be included in the compilation. */ 10 // "allowJs": true, /* Allow javascript files to be compiled. */ 11 // "checkJs": true, /* Report errors in .js files. */ 12 // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */ 13 // "declaration": true, /* Generates corresponding '.d.ts' file. */ 14 // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 15 // "sourceMap": true, /* Generates corresponding '.map' file. */ 16 // "outFile": "./", /* Concatenate and emit output to single file. */ 17 // "outDir": "./", /* Redirect output structure to the directory. */ 18 // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 19 // "composite": true, /* Enable project compilation */ 20 // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 21 // "removeComments": true, /* Do not emit comments to output. */ 22 // "noEmit": true, /* Do not emit outputs. */ 23 // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 24 // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 25 // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 26 27 /* Strict Type-Checking Options */ 28 "strict": true, /* Enable all strict type-checking options. */ 29 // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 30 // "strictNullChecks": true, /* Enable strict null checks. */ 31 // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 32 // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 33 // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 34 // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 35 // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 36 37 /* Additional Checks */ 38 // "noUnusedLocals": true, /* Report errors on unused locals. */ 39 // "noUnusedParameters": true, /* Report errors on unused parameters. */ 40 // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 41 // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 42 // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ 43 // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */ 44 // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */ 45 46 /* Module Resolution Options */ 47 // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 48 // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 49 // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 50 // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 51 // "typeRoots": [], /* List of folders to include type definitions from. */ 52 // "types": [], /* Type declaration files to be included in compilation. */ 53 // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 54 "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 55 // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 56 // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 57 58 /* Source Map Options */ 59 // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 60 // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 61 // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 62 // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 63 64 /* Experimental Options */ 65 // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 66 // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 67 68 /* Advanced Options */ 69 "skipLibCheck": true, /* Skip type checking of declaration files. */ 70 "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ 71 } 72 }
1、include
用来指定哪些路径下的ts文件需要被编译
1 { 2 "include": [ 3 "./src/**/*" 4 ] 5 }
- **表示任意文件夹
- *表示任意文件
2、exclude
1 { 2 "exclude": [ 3 "node_modules", 4 "./src/hello/**/*" 5 ] 6 }
3、extends
继承其他配置文件
1 { 2 "extends": "./config/base" 3 }
4、files
指定需要编译的文件
1 { 2 "files": [ 3 "core.ts", 4 "sys.ts", 5 "types.ts" 6 ] 7 }
1 { 2 "compilerOptions": [ 3 "target": "es2015", /* 指定ECMAScript目标版本 */ 4 "module": "es6", /* 指定生成哪个模块系统代码 */ 5 "lib": ["dom", "es6"], /* 指定项目中用到的库 */ 6 "outDir": "./dist", /* 指定编译后文件所在目录 */ 7 "outFile": "./dist/app.js", /* 将代码合并成一个文件 */ 8 "allowJs": true, /* 是否对js文件进行编译 */ 9 "checkJs": true, /* 是否检查js语法 */ 10 "removeComments": true, /* 是否移除注释 */ 11 "noEmit": true, /* 是否生成编译后的文件 */ 12 "noEmitOnError": true, /* 有错误时不生成编译后的文件 */ 13 "alwaysStrict": true, /* 编译后的文件是否使用严格模式 */ 14 ] 15 }
四、webpack配置文件
安装webpack、webpack-cli、ts-loader
1 npm i -D webpack webpack-cli ts-loader
1 module: { 2 rules: [ 3 { 4 test: /\.ts$/, 5 use: "ts-loader", 6 exclude: /node_modules/ 7 } 8 ] 9 }
五、类
1、静态属性
1、类中直接定义的属性是实例属性,使用时要new
2、使用static开头的属性是静态属性(类属性),无需创建对象,可以直接通过类使用
1 class Person{ 2 // 定义实例属性 3 name: string = "张三"; 4 5 // 静态属性,在属性前加static关键词 6 static age: number = 18; 7 } 8 9 const per = new Person(); 10 11 // 使用实例属性 12 console.log(per.name); 13 // 使用静态属性 14 console.log(Person.age);
2、只读属性
只读属性只能读取,不能设置
1 class Person{ 2 // 定义实例属性 3 name: string = "张三"; 4 5 // 静态属性,在属性前加static关键词 6 static age: number = 18; 7 8 // 只读属性,属性前加readonly 9 readonly gender: string = "男" 10 } 11 12 const per = new Person(); 13 14 console.log(per.gender);
3、构造器
constructor,也叫构造函数,会在对象创建时调用,也就是new的时候
1 class Dog{ 2 name: string; 3 age: number; 4 5 constructor(name: string, age: number){ 6 7 console.log("我是构造函数内容"); 8 9 // 在实例方法中,this表示当前的实例 10 // 在构造函数中,当前对象就是新建的那个对象(per) 11 console.log(this); 12 13 // 可以通过this向新建的对象中添加属性 14 this.name = name; 15 this.age = age; 16 } 17 } 18 19 const dog = new Dog("小黑", 4); 20 const dog1 = new Dog("小白", 2);
4、继承
将多个类中的共有方法写在一个父类中
1 class Animal{ 2 name: string; 3 age: number; 4 constructor(name: string, age: number){ 5 this.name = name; 6 this.age = age; 7 } 8 sayHello(){ 9 console.log("Hello,大家好!") 10 } 11 } 12 13 class Dog extends Animal{ 14 run(){ 15 console.log(`${this.name}在跑~~`) 16 } 17 } 18 19 class Cat extends Animal{ 20 21 } 22 23 const dog = new Dog("旺财", 4); 24 const cat = new Cat("咪咪", 2); 25 dog.sayHello(); 26 cat.sayHello(); 27 28 // 调用自己的方法 29 dog.run();
5、super
1 class Animal{ 2 name: string; 3 constructor(name: string){ 4 this.name = name; 5 } 6 sayHello(){ 7 console.log("Hello,大家好!") 8 } 9 } 10 11 class Dog extends Animal{ 12 sayHello(){ 13 // super代表当前类的父类 14 super.sayHello(); 15 } 16 } 17 18 class Cat extends Animal{ 19 age: number; 20 // 如果在子类中写了构造函数,必须对父类的构造函数进行调用 21 constructor(name: string, age: number){ 22 // super代表调用父类构造函数 23 super(name); 24 this.age = age; 25 } 26 } 27 28 const dog = new Dog("旺财"); 29 const cat = new Cat("咪咪");
6、抽象类
-
-
抽象类中可以创建抽象方法
-
抽象方法没有函数体
-
-
关键词:abstract
1 abstract class Animal{ 2 name: string; 3 constructor(name: string){ 4 this.name = name; 5 } 6 // 定义抽象方法 7 abstract sayHello(): void; 8 } 9 10 class Dog extends Animal{ 11 sayHello(){ 12 console.log("Hello,dog") 13 } 14 }
六、接口
-
-
接口中的所有属性都不能有实际值
-
接口中的所有方法都是抽象方法
-
可以使类实现一个接口,实现接口就是满足接口的要求
-
-
1 interface myInter{ 2 name: string; 3 // 接口中的方法是抽象方法,没有方法体 4 sayHello(): void; 5 } 6 7 class MyClass implements myInter{ 8 name: string; 9 constructor(name: string){ 10 this.name = name; 11 } 12 sayHello(){ 13 console.log("大家好") 14 } 15 }
1 interface myInterface{ 2 name: string; 3 age: number; 4 } 5 6 interface myInterface{ 7 gender: string 8 } 9 10 const obj: myInterface = { 11 name: "王五", 12 age: 33, 13 gender: "男" 14 }