tsconfig.json配置文件
生成tsconfig.json文件
这个文件是通过tsc --init命令生成的
配置详细
"compilerOptions": {
"incremental": true, // TS编译器在第一次编译之后会生成一个存储编译信息的文件,第二次编译会在第一次的基础上进行增量编译,可以提高编译的速度
"tsBuildInfoFile": "./buildFile", // 增量编译文件的存储位置
"diagnostics": true, // 打印诊断信息
"target": "ES5", // 目标语言的版本
"module": "CommonJS", // 生成代码的模板标准
"outFile": "./app.js", // 将多个相互依赖的文件生成一个文件,可以用在AMD模块中,即开启时应设置"module": "AMD",
"lib": ["DOM", "ES2015", "ScriptHost", "ES2019.Array"], // TS需要引用的库,即声明文件,es5 默认引用dom、es5、scripthost,如需要使用es的高级版本特性,通常都需要配置,如es8的数组新特性需要引入"ES2019.Array",
"allowJS": true, // 允许编译器编译JS,JSX文件
"checkJs": true, // 允许在JS文件中报错,通常与allowJS一起使用
"outDir": "./dist", // 指定输出目录
"rootDir": "./", // 指定输出文件目录(用于输出),用于控制输出目录结构
"declaration": true, // 生成声明文件,开启后会自动生成声明文件
"declarationDir": "./file", // 指定生成声明文件存放目录
"emitDeclarationOnly": true, // 只生成声明文件,而不会生成js文件
"sourceMap": true, // 生成目标文件的sourceMap文件
"inlineSourceMap": true, // 生成目标文件的inline SourceMap,inline SourceMap会包含在生成的js文件中
"declarationMap": true, // 为声明文件生成sourceMap
"typeRoots": [], // 声明文件目录,默认时node_modules/@types
"types": [], // 加载的声明文件包
"removeComments":true, // 删除注释
"noEmit": true, // 不输出文件,即编译后不会生成任何js文件
"noEmitOnError": true, // 发送错误时不输出任何文件
"noEmitHelpers": true, // 不生成helper函数,减小体积,需要额外安装,常配合importHelpers一起使用
"importHelpers": true, // 通过tslib引入helper函数,文件必须是模块
"downlevelIteration": true, // 降级遍历器实现,如果目标源是es3/5,那么遍历器会有降级的实现
"strict": true, // 开启所有严格的类型检查
"alwaysStrict": true, // 在代码中注入'use strict'
"noImplicitAny": true, // 不允许隐式的any类型
"strictNullChecks": true, // 不允许把null、undefined赋值给其他类型的变量
"strictFunctionTypes": true, // 不允许函数参数双向协变
"strictPropertyInitialization": true, // 类的实例属性必须初始化
"strictBindCallApply": true, // 严格的bind/call/apply检查
"noImplicitThis": true, // 不允许this有隐式的any类型
"noUnusedLocals": true, // 检查只声明、未使用的局部变量(只提示不报错)
"noUnusedParameters": true, // 检查未使用的函数参数(只提示不报错)
"noFallthroughCasesInSwitch": true, // 防止switch语句贯穿(即如果没有break语句后面不会执行)
"noImplicitReturns": true, //每个分支都会有返回值
"esModuleInterop": true, // 允许export=导出,由import from 导入
"allowUmdGlobalAccess": true, // 允许在模块中全局变量的方式访问umd模块
"moduleResolution": "node", // 模块解析策略,ts默认用node的解析策略,即相对的方式导入
"baseUrl": "./", // 解析非相对模块的基地址,默认是当前目录
"paths": { // 路径映射,相对于baseUrl
// 如使用jq时不想使用默认版本,而需要手动指定版本,可进行如下配置
"jquery": ["node_modules/jquery/dist/jquery.min.js"]
},
"rootDirs": ["src","out"], // 将多个目录放在一个虚拟目录下,用于运行时,即编译后引入文件的位置可能发生变化,这也设置可以虚拟src和out在同一个目录下,不用再去改变路径也不会报错
"listEmittedFiles": true, // 打印输出文件
"listFiles": true// 打印编译的文件(包括引用的声明文件)
}
// 指定一个匹配列表(属于自动指定该路径下的所有ts相关文件)
"include": [
"src/**/*"
],
// 指定一个排除列表(include的反向操作)
"exclude": [
"demo.ts"
],
// 指定哪些文件使用该配置(属于手动一个个指定文件)
"files": [
"demo.ts"
]
1.include
指定编译文件默认是编译当前目录下所有的ts文件
2.exclude
指定排除的文件
3.target
指定编译js 的版本例如es5 es6
4.allowJS
是否允许编译js文件
5.removeComments
是否在编译过程中删除文件中的注释
6.rootDir
编译文件的目录
7.outDir
输出的目录
8.sourceMap
代码源文件
9.strict
严格模式
10.module
默认common.js 可选es6模式 amd umd 等
theme: channing-cyan highlight: a11y-dark
装饰器
Decorator 装饰器是一项实验性特性,在未来的版本中可能会发生改变 它们不仅增加了代码的可读性,清晰地表达了意图,而且提供一种方便的手段,增加或修改类的功能 若要启用实验性的装饰器特性,你必须在命令行或tsconfig.json里启用编译器选项
"experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
装饰器定义
装饰器是一种特殊类型的声明,它能够被附加到类声明,方法, 访问符,属性或参数上。
class A {
constructor{
}
}
定义一个类装饰器函数 他会把ClassA的构造函数传入你的watcher函数当做第一个参数
const watcher : ClassDecorator = (target: Function)=> {
target.prototype.getParams = <T>(params:T):T => {
return params
}
}
使用的时候 直接通过@函数名使用
@watcher
class A {
constructor{
}
}
验证
const a = new A();
console.log((a as any).getParams('123'));
装饰器工厂
其实也就是一个高阶函数 外层的函数接受值 里层的函数最终接受类的构造函数
const watcher = (name: string): ClassDecorator => {
return (target: Function) => {
target.prototype.getParams = <T>(params: T): T => {
return params
}
target.prototype.getOptions = (): string => {
return name
}
}
}
@watcher('name')
class A {
constructor() {
}
}
const a = new A();
console.log((a as any).getParams('123'));
装饰器组合
就是可以使用多个装饰器
const watcher2 = (name:string) => {
return (target: Function) => {
target.prototype.getNames = ():string => {
return name
}
}
}
const watcher = (name: string): ClassDecorator => {
return (target: Function) => {
target.prototype.getParams = <T>(params: T): T => {
return params
}
target.prototype.getOptions = (): string => {
return name
}
}
}
@watcher2('name2')
@watcher('name')
class A {
constructor() {
}
}
const a = new A();
console.log((a as any).getParams('123'));
方法装饰器
返回三个参数
- 1.对于静态成员来说是类的构造函数,对于实例成员是类的原型对象。
- 2.成员的名字。
- 3.成员的属性描述符。
[
{},
'setParasm',
{
value: [Function: setParasm],
writable: true,
enumerable: false,
configurable: true
}
]
const met:MethodDecorator = (...args) => {
console.log(args);
}
class A {
constructor() {
}
@met
getName ():string {
return '小满'
}
}
const a = new A();
属性装饰器
返回两个参数
- 对于静态成员来说是类的构造函数,对于实例成员是类的原型对象。
- 属性的名字。
[ {}, 'name', undefined ]
const met:PropertyDecorator = (...args) => {
console.log(args);
}
class A {
@met
name:string
constructor() {
}
}
const a = new A();
参数装饰器
返回三个参数
- 对于静态成员来说是类的构造函数,对于实例成员是类的原型对象。
- 成员的名字。
- 参数在函数参数列表中的索引。
[ {}, 'setParasm', 0 ]
const met:ParameterDecorator = (...args) => {
console.log(args);
}
class A {
constructor() {
}
setParasm (@met name:string = '213') {
}
}
const a = new A();
- 用装饰器,实现一个简便的发送网络请求的Http类
import axios from 'axios'
// 首先定义一个类
console.log('------------------------------------------------')
const Base = (name:string) => {
const fn:ClassDecorator = (target) => {
// console.log(target);
target.prototype.name = '张三'
target.prototype.fn = () => {
console.log(name);
}
}
return fn
}
const Get = (url:string) => {
const fn:MethodDecorator = (target,propertyKey,descriptor:PropertyDescriptor) => {
console.log(target,propertyKey,descriptor);
axios.get(url).then(res=>{
descriptor.value(res.data)
})
}
return fn
}
@Base('李四')
class Http {
@Get('http://kecat.top/post/ts-1%E5%90%84%E7%A7%8D%E7%B1%BB%E5%9E%8B.md')
getPost(data:any):void{
console.log(data);
}
}
const http = new Http() as any
http.getPost()
泛型
泛型在TypeScript 是很重要的东西 例如vue3 是用ts编写的 里面用到了非常多的泛型
泛型函数
一个是数字类型的函数,另一个是字符串类型的函数,其实就是类型不同, 实现的功能是一样的,这时候我们就可以使用泛型来优化
function num111 (a:number, b:number): Array<number> {
return [a,b]
}
num111(1,2)
function str111 (a:string,b:string):Array<string>{
return [a,b]
}
str111('1','2')
- 泛型优化
语法为函数名字后面跟一个<参数名> 参数名可以随便写 例如我这儿写了T 当我们使用这个函数的时候把参数的类型传进去就可以了 (也就是动态类型)
function Add<T>(a:T,b:T):Array<T>{
return [a,b]
}
Add(1,2)
Add('1','2')
// Add(1,'2') // 报错,类型“string”的参数不能赋给类型“number”的参数。
我们也可以使用不同的泛型参数名,只要在数量上和使用方式上能对应上就可以。
function Sub<T,K>(a:T,b:K):Array<T|K>{
return [a,b]
}
Sub(1,'2')
Sub('111',false)
定义泛型接口
声明接口的时候 在名字后面加一个<参数> 使用的时候传递类型
interface MyInter<T> {
(arg:T):T
}
function fn<T>(arg:T):T{
return arg
}
let result:MyInter<number> = fn
result(123)
对象字面量泛型
let foo: { <T>(arg:T):T }
// foo = <T>(arg:T):T => {
// return arg
// }
foo = function<T>(arg:T):T {
return arg
}
foo('123')
泛型约束
我们期望在一个泛型的变量上面,获取其length参数,但是,有的数据类型是没有length属性的
function getLength<T>(arg:T) {
// return arg.length // 类型“T”上不存在属性“length”
}
- 这时候我们就可以使用泛型约束
于是,我们就得对使用的泛型进行约束,我们约束其为具有length属性的类型,这里我们会用到interface,代码如下
interface Len {
length:number
}
function getLength2<T extends Len>(arg:T):number{
return arg.length
}
getLength2('123')
使用keyof 约束对象
- 其中使用了TS泛型和泛型约束。
- 首先定义了T类型并使用extends关键字继承object类型的子类型,
- 然后使用keyof操作符获取T类型的所有键,
- 它的返回 类型是联合 类型,
- 最后利用extends关键字约束 K类型必须为keyof T联合类型的子类型
function prop<T, K extends keyof T>(obj:T,key:K){
return obj[key]
}
let o = {
a:1,b:2
}
prop(o,'a')
prop(o,'b')
// prop(o,'c') // 报错, 类型“"c"”的参数不能赋给类型“"a" | "b"”的参数。ts(2345)
泛型类
声明方法跟函数类似名称后面定义<类型> 使用的时候确定类型
new Sub<number>()
class Sub2<T>{
attr: T[] = [];
add (a:T):T[] {
return [a]
}
}
let s = new Sub2<number>()
s.attr = [1,2,3]
s.add(123)
let str = new Sub2<string>()
str.attr = ['1','2','3']
str.add('123')