Typescript基础

TypeScript入门

1. 变量的类型推断

let a='hello' // 推断为string
a=1 //ts赋值时第一次值就已经确定了,不可以赋值其他类型 

2.数组的类型推断

const arr=['',1,true]  //推断为 string|number|boolean
arr.push() // 可以push上面三种类型

3.对象的类型推断

const user ={name:''}
user.name // 会对对象中的进行类型推断

4.基础的变量声明

let a:number
let b:string
let c:boolean
let d:string[]|number[]|boolean[]

5.对象的类型声明

let a:object // 没有意义
let b:{name:string,age:number,url?:string} // url?是可选的

6.组合类型的声明

let a:string|number
let b:(string|number)[] 

7.类型断言

let a:unknown=''
let b:string=a // 报错
let c:string=a as string // 类型断言

let d:string=''
let e:number= hd as unknown as number // 用unknown进行中转

8.void类型和never类型

function a():void{ // 返回是undefined和null
}
function b():never{ // 没有返回值
// 抛出异常
}

9.函数类型以及参数声明

const func:function
func=()=>''
function sum(a:number,b:number,c:number=0.6):number{ // 普通参数
    return a+b+c
}

function add(user:{name:string,age:number}):void{
    console.log('添加用户')
}

10.type对函数参数进行声明

type userType={name:string,age:number}

let addUser(user:userType):void{
    console.log('添加用户')
}

11.函数的结构定义

type userTypeFun=(user:{name:string,age:number})=>number // 函数type声明
let hd:(user:{name:string,age:number})=>number // 结构声明
hd:userTypeFun=(user:{name:string,age:number})=>{ // 函数声明(结构声明和函数type声明只要一样)
    return 1
}
hd({name:'',age:1}) // 函数调用

12.剩余参数在TS中的使用

function sum(...args:number[]):number{
 return   args.reduce((s,n)=>s+n,0)
}
console.log(sum(1,2,3,4))

13.元组(位置类型对应)

let tuple:[string,number,boolean]=['',1,true]

14.联合交叉类型

// &优先级大于|
   let obj:{name:string}&{age:string}|{name:number}&{age:string} 

TypeScript的枚举和断言

1.Enum枚举类型

enum sexType{
    A =6, // 默认是0
    B  // 默认是1(递增)
}
console.log(sexType.B)

2.as断言

function A(arg:boolean):string|number{
    return arg?'':1
}
let B=A(true) as string // 断定是字符串

3.const断言(只读)

let a:string='A'
let b='C' as const // 不可改变
const arr=[a,b,1,'',true] as const // 转换成只读元组  const arr=<const>[a,b]

const obj={name:1} as const // 转换成只读类型

4.解构中使用const断言

function hd(){
    let a=''
    let b=(x:number,y:number):number=>x+y4
    return [a,b] as [typeof a,typeof b] // as const 
}

const [a,b]=hd() as [string,Function] // 不断言调用函数会出错
console.log((b as Function)(1,2)) 
// 上面的断言只要使用一个

5.非空断言

const a:HTMLDivElement=document.querySelector('.hd') as HTMLDivElement // 不加断言会报错 
const a:HTMLDivElement=document.querySelector('.hd')! // !等于as HTMLDivElement

6.DOM的类型推断和断言处理

const body:HTMLBodyElement=document.querySelector('body')!
const div:Element=document.querySelector('.a') as HTMLDivElement
Element 普通元素
HTMLDivElement div元素
HTMLBodyElement body元素
HTMLLinkElement a元素

7.class构造函数的强制断言

class Hd{
    el:HTMLDivElement
    constructor(el:HTMLDivElement){
        this.el=el
    }
    html(){
        return this.el.innerHTML
    }
}

const el=document.querySelector('.a') as HTMLDivElement
new Hd(el)

8.DOM事件的处理

const btn:HTMLButtonElement=document.querySelector('.btn') as HTMLButtonElement
btn.addEventListener('click',(e:Event)=>{
    e.preventDefault()
    // 完美的提示效果
    const body=document.querySelector('body') as HTMLBodyElement
    body.insertAdjacentHTML('beforeend','<h1></h1>')
})

TypeScript类与接口

1.TS来约束类

class User{
    name:string
    age:number
    constructor(n:string,a:number){
        this.name=n
        this.age=a
    }
    info():string{
        return `${this.name}---${this.age}`
    }
}
const hd=new User('qql',22)
console.log(hd.info())

2.public修饰符(外部,本类和子类使用)

// 没有写public默认public
//  属性是对象独有的,方法在原型上
class User{
   public name:string
   public age:number
    constructor(n:string,a:number){
        this.name=n
        this.age=a
    }
    public info():string{
        return `${this.name}---${this.age}`
    }
}
const hd=new User('qql',22)
console.log(hd.info())

3.protected修饰符(本类和子类使用)

// protected受包含的修饰符,只能在类里面调用
class User{
protected name:string
   protected age:number
    constructor(n:string,a:number){
        this.name=n
        this.age=a
    }
    protected info():string{
        return `${this.name}---${this.age}`
    }
}
const hd=new User('qql',22)
// console.log(hd.info())  报错

// 子类中还是可以调用受保护的模块
class U extends User{
    constructor(n:string,a:number){
        super(n,a)
        this.name=n,
        this.age=a
    }
}

4.private修饰符(本类使用)

// private修饰符私有的修饰符只能在这个类里面调用
class User{
    private name:string
    private age:number
    constructor(n:string,a:number){
        this.name=n
        this.age=a
    }
    private info():string{
        return `${this.name}---${this.age}`
    }
}
// 子类里面也不可以调用
class U extends User{
    constructor(n:string,a:number){
        super(n,a)
        // this.name=n
        // this.age=a 报错
    }
}
const hd=new User('qql',22)
// console.log(hd.info) 报错

5.类中重写继承父类方法

class User{
     name:string
     age:number
    constructor(n:string,a:number){
        this.name=n
        this.age=a
    }
   protected info():string{
        return `${this.name}---${this.age}`
    }
   protected info2():string{
        return `${this.name}---${this.age}`
    }
    private info3():string{
        return `${this.name}---${this.age}`
    }
}

class U extends User{
    constructor(n:string,a:number){
        super(n,a)
    }
    // 子类重写父类的方法时只能降低拥有度,私有的方法无法重写

    /* private info(): string {
       return `${this.name}---${this.age}`
     } 
        private info3():string{
         return `${this.name}---${this.age}`
     }
   */
     protected  info(): string {
        return `${this.name}---${this.age}`
      } 
      public info2(): string {
        return `${this.name}---${this.age}`
      }
    
}

6.readonly修饰符

class Axios{
    public readonly site:string=''
    public constructor(site:string) {
        this.site=site
    }
}
const b=new Axios('') // 构造函数初始化可以修改
b.site='' // readonly后的变量不可修改

7.类构造方法constructor

// 构造方法参数中的变量加了修饰符就相当于constructor外定义了public name:string this.name=name 
class User{
    // public name:string
    constructor( public name:string){
    //  this.name=name 
    }
}

8.static静态属性语句

// 不需要实例初始化的放在静态中
class User{
    static site:string=''
}
const instance =new User()
instance.site // 实例无法调用静态方法
console.log(User.site) // 构造函数可以调用

9.Typescript实现单例模式

// 一个类只能创建一个实例
class Axios{
    private static instance: Axios |null=null
    private constructor() {
        console.log('构造方法')
    }
    static make():Axios{
        if(Axios.instance===null){
            console.log('创建axios')
          Axios.instance=new Axios()
        }
       return Axios.instance
    }
}
const instance=Axios.make()

10.访问器get和set

class User{
    private _name:string
    constructor(name:string){
        this._name=name
    }
    public get name():string{
        return this._name
    }
    public set name(name:string){
     this._name=name
    }
}

const A =new User('qql')
A.name='qq' // 调用set访问器
console.log(A.name) // 调用get访问器

11.Typescript抽象类

// 抽象类中必须有规范方法,也可以有普通方法
abstract class Animation{
  abstract name:string
  abstract move():void
  protected getPos():number[]{
    return [100,300]
  }
}
// 继承抽象类要完成抽象修饰东西的实现(方法,属性)
class Tank extends Animation{
    name:'敌方坦克'
    public move():void{
        console.log('敌方坦克移动')
    }
}

12.类实现interface接口

interface Animati{
    end():void
  }
interface Animatio{
    name:string
    move():void
  }
  // 实现接口要完成接口中定义的(方法,属性)
  class Tank implements Animatio,Animati{
      name:'敌方坦克'
      public move():void{
          console.log('敌方坦克移动')
      }
      public end():void{
          console.log('游戏结束')
      }
  }
  

13.interface接口对对象的约束

interface Userinterface{
    name:string
    age:number
    weight?:number // 可选属性
    info():string 
    [key:string]:any // 其他属性可选
}
let hd:Userinterface={
    name:'qql',
    age:18,
    info(){
        return `${this.name}-${this.age}`
    }
}

14.interface接口对参数的约束

type userType={name:string,age:number}
interface userinterface{
    name:string
    age:number
}
// 函数参数,返回类型
function isLock(user:userType):userType{
    return {name:'qql',age:19}
}
// 类的构造器参数
class ISlock{
    public info:userinterface
    constructor(info:userinterface){
        this.info=info
    }
}

15.interface接口对数组的约束

interface userinterface{
    name:string
    age:number
}
const hd:userinterface={
    name:'qql',
    age:18
}
const users:userinterface[]=[hd]

16.interface接口案例

interface PayInterface{
    handle(price:number):void
}
class AliPay implements PayInterface{
    public handle(price:number):void{
     console.log('支付宝付款',price)
    }
}
class Wepay implements PayInterface{
    public handle(price:number):void{
        console.log('微信付款',price)
    }
}
function pay(type:string,price:number){
    let pay:PayInterface
    switch(type){
        case 'alipay':
            pay=new AliPay()
            break
        case 'wepay':
            pay=new Wepay()
    }
    pay.handle(price)
}

pay('alipay',100)

17.interface声明函数

interface Pay{
(private:number):boolean
}
const we:Pay=(price:number)=>true

18.interface接口的合并

// 使用继承合并
interface A{
    name:string
}
interface B extends A{
    age:number
}
// 使用同名合并
interface C{
    name:string
}
interface C{
    age:number
}

19.type和interface差异

// 不同
// type可以声明基本类型
type IsAdmin=boolean
//  type合并于interface不同
type name={
    name:string
}
type age={
    age:string
}
type User=age&name
// 相同
type name={
    name:string
}
type age={
    age:string
}
type User=age&name

class person implements User{
    name:""
    age:''
}

20.ts中更新全局接口interface

// 新建 xx.d.ts类型的文件,对同名的接口进行扩展 
interface Window{
    myname:string // 让全局的Window接口上有myname这个属性
}

// ts中提供了window类型 其他模块使用window可以调用myname
export{}
function Person(this:Window,name:string){
  this.myname=name 
}

TypeScript泛型

1.什么是泛型

function a(a:string):string{
    return a
}
function b(b:boolean):boolean{
    return b
}
let a1=a('')
let b1=b(true)
// 动态设置类型
function c<T>(c:T):T{
    return c
}
let c1=c<string>('')
let c2=c<boolean>(true)

2.泛型的继承

// 泛型T的继承,要求后面传递的类型一定要满足继承的类型
function getLength<T extends {length:number}>(l:T):number{
    return l.length
}
function getLength<T>(l:T[]):number{
    return l.length
}

3.泛型在类中的使用

class A<T>{
    data:T[]=[]
    push(...items:T[]){
        this.data.push(...items)
    }
    length():number{
        return this.data.length
    }
}
const B=new A<number>()
B.push(1,2,3)
console.log(B.length())

4.构造函数中使用泛型


class User<T>{
    public constructor( private _user:T){}
    public user():T{
        return this._user
    }
}
interface Userinterface{
    name:string,
    age:number
}
const obj=new  User<Userinterface>({name:'A',age:12})
console.log(obj.user())

5.接口使用泛型

interface Articleinterface<T,C>{
    title:string
    isLock:T
    comments:C[]
}
type commentType={
    content:string
}
const hd:Articleinterface<boolean,commentType>={
    title:'',
    isLock:true,
    comments:[{content:''}]
}

TypeScript装饰器

1.打开ts的装饰器配置项

tsc --init
配置文件中搜索decora
打开    "experimentalDecorators": true,                 
    "emitDecoratorMetadata": true,  

2.类装饰器

// 给类中添加公共方法
const moveDecorator:ClassDecorator=(target:Function)=>{
  target.prototype.getPosition=():{x:number,y:number}=>{
    return {x:100,y:100}
  }
}

@moveDecorator
class Tank{}
// moveDecorator(Tank) === @moveDecorator
const t=new Tank()
console.log((t as any).getPosition())

3.类装饰器的叠加

const moveDecorator:ClassDecorator=(target:Function)=>{
  target.prototype.getPosition=():{x:number,y:number}=>{
    return {x:100,y:100}
  }
}

const musicDecorator:ClassDecorator=(target:Function)=>{
    target.prototype.playMusic=():void=>{
        console.log('播放音乐')
    }
}

@musicDecorator
@moveDecorator
class Tank{}
// moveDecorator(Tank)
const t=new Tank()

console.log((t as any).getPosition(),(t as any).playMusic())

4.类装饰器完成消息响应

const MessageDecorator:ClassDecorator=(target:Function)=>{
    target.prototype.message=(content:string)=>{
        console.log(content)
}
}

@MessageDecorator
class LoginController{
    public login(){
        console.log('登录业务')
        this.message('恭喜登录成功')
    }
}

new LoginController().login()

5.类装饰器工厂

const  MessageDecoratorFactory=(name:string):ClassDecorator=>{
   return (target:Function)=>{
    target.prototype.message=(content:string)=>{
        console.log(name+content)
 }
}
}

@MessageDecoratorFactory('qql')
class LoginController{
    public login(){
        console.log('登录业务')
        this.message('恭喜登录成功')
    }
}

new LoginController().login()

6.方法装饰器

/**
 * 
 * @param target 对象原型
 * @param propertyKey 使用装饰器的函数名
 * @param descriptor.value 使用装饰器的方法,多用于重写,调用
 */
 const showDecorator:MethodDecorator=(target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor)=>{

descriptor.value=()=>{ 
    console.log('a')
}
}

class User{
    @showDecorator
    public show(){
      console.log(1)
    }
}
User.show()

7.方法装饰器阻止函数第二次声明(静态函数)

const showDecorator:MethodDecorator=(target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor)=>{
    // descriptor: {value: [Function: show],writable: true,enumerable: false,configurable: true}
descriptor.writable=false // 不让其函数再次声明
}

class User{
    @showDecorator
    public static show(){
      console.log(1)
    }
}
User.show()

8.使用方法装饰器给一段文字添加背景

const highlightDecorator:MethodDecorator=(target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor)=>{
    // descriptor: {value: [Function: show],writable: true,enumerable: false,configurable: true}
  const method=descriptor.value
  descriptor.value=()=>{
    return `<h1 style="background:black;color:white">${method()}</h1>`
  }
}

class User{
    @highlightDecorator
    public static show(){
      return 'aaaaaa'
    }
}
console.log(User.show())

9.方法延迟装饰器

const SleepDecorator:MethodDecorator=(target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor)=>{
    // descriptor: {value: [Function: show],writable: true,enumerable: false,configurable: true}
  const method=descriptor.value
  descriptor.value=()=>{
  setTimeout(()=>{
    method()
  },2000)
  }
}

class User{
    @SleepDecorator
    public static show(){
      console.log('10')
    }
}
User.show()

10.方法装饰器工厂实现延迟


const SleepDecoratorFactory=(times:number)=>{
    return(target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor)=>{
        // descriptor: {value: [Function: show],writable: true,enumerable: false,configurable: true}
      const method=descriptor.value
      descriptor.value=()=>{
      setTimeout(()=>{
        method()
      },times)
      }
    }
}


class User{
    @SleepDecoratorFactory(2000)
    public static show(){
      console.log('10')
    }
}
User.show()

11.方法装饰器进行异常处理

const ErrorDecortator=  (target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor)=>{
  const method=descriptor.value
  descriptor.value=()=>{
    try{
        method()
       } catch(e){
         console.log('错')
       }       
  }
}

class User{
    @ErrorDecortator
    public  show(){
      throw new Error('出错了')
    }
}
new User().show()

12.方法装饰器工厂对异常输出信息定制

const ErrorDecortatorFactory=(title:string='出错了')=>{
    return(target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor)=>{
        const method=descriptor.value
        descriptor.value=()=>{
          try{
              method()
             } catch(e){
               console.log(title)
             }       
        }
      }
}

class User{
    @ErrorDecortatorFactory()
    public static show(){
      throw new Error('出错了')
    }
}
 User.show()

13.方法装饰器完成权限管理

type userType={
    name:string
    isLogin:boolean
    Authority:string[]
}
const user:userType={
    name:'admin',
    isLogin:true,
    Authority:['store'] // 用户有的权限
}
const AccesssDecortorFactory=(keys:string[]):MethodDecorator=>{
    return (target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor)=>{
        const method=descriptor.value
        const validate=()=>keys.every(k=>{
            return user.Authority.includes(k)
        })    
        descriptor.value=()=>{
            if(user.isLogin===true&&validate()){
                return method()
            }
            console.log('请登录')
        }
}
}
class Article{
    show(){
      console.log('显示文章')
    }
    @AccesssDecortorFactory(['store','1']) // 装饰器要求的权限,['store‘]权限标识
    store(){
      console.log('保存文章')
    }
}
new Article().show()
new Article().store()

14.方法装饰器模拟发送请求

const RequestDecorator=(url:string):MethodDecorator=>{
    return (target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor)=>{
        const method=descriptor.value     
        new Promise(resolve=>{
            setTimeout(()=>{
                resolve({name:"qql",age:18})
            },2000)
        }).then(user=>{
            method(user)
        })
    }
}

class User{
   @RequestDecorator('http:xx/xx/api')
    all(users:any[]){
        console.log(users)
    }
}

15.属性装饰器

/**
 * 
 * @param target 使用属性装饰器的属性名
 * @param propertyKey 属性的名称
 */
const PropDecorator:PropertyDecorator=(target: Object, propertyKey: string | symbol)=>{ // 属性装饰器
}
class A {
    @PropDecorator
    public title :string | undefined='1'
}

16.属性装饰器实现大小写转换

const lowerDecorator:PropertyDecorator=(target: Object, propertyKey: string | symbol)=>{
    let value:string
Object.defineProperty(target,propertyKey,{
    get:()=>{
        console.log('我被读取了')
        return value.toLocaleLowerCase()//变成小写
    },
    set:v=>{
        value=v
    }
})
}

class A{
    @lowerDecorator
    public title:string|undefined
}
new A().title='ASDASDAS'
console.log(new A().title)

17.属性装饰器实现随机颜色

const RandomDecotor:PropertyDecorator=(target: Object, propertyKey: string | symbol)=>{
    const colors:string[]=['red','black','yellow']
    Object.defineProperty(target,propertyKey,{
        get(){
            return colors[Math.floor(Math.floor(Math.random()*colors.length))]
        }
    })
}

class A{
    @RandomDecotor
    color:string|undefined
    public draw(){
        console.log(this.color)
    }
}
new A().draw()

18.参数装饰器

/**
 * 
 * @param target 对象原型
 * @param propertyKey 使用装饰器的函数名
 * @param parameterIndex 第几个参数使用了参数装饰器
 */
const ParameDecorator:ParameterDecorator=(target: Object, propertyKey: string | symbol, parameterIndex: number)=>{// 参数装饰器
    console.log(args)
}
class A {
    show(id:number=1,@ParameDecorator content:string){}
}

19.参数装饰器的元数据的简单使用

// 安装 yarn add reflect-metadata
import 'reflect-metadata'
let A={
    name:'qql'
}
Reflect.defineMetadata('qq',{url:'http:xxxx/xxx'},A ,'name')
console.log(Reflect.getMetadata('qq',A,'name'))

20.参数的简单验证

import 'reflect-metadata'
/**
 * 
 * @param target 对象原型
 * @param propertyKey 使用装饰器的函数名
 * @param parameterIndex 第几个参数使用了参数装饰器
 */
 let requiredParams:number[]=[]
const RequiredDecorator:ParameterDecorator=(target: Object, propertyKey: string | symbol, parameterIndex: number)=>{
    // 对参数进行验证
    requiredParams.push(parameterIndex)
    // 元数据记录
    Reflect.defineMetadata('required',requiredParams,target,propertyKey)
}
/**
 * 
 * @param target 对象原型
 * @param propertyKey 使用装饰器的函数名
 * @param descriptor.value 使用装饰器的方法,多用于重写
 */
const valDecorator:MethodDecorator=(target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor)=>{
    const method=descriptor.value
    descriptor.value=function(){
      const Params:number[]=Reflect.getMetadata('required',target,propertyKey)
      Params.forEach(keys=>{
       if(Params.length>arguments.length||arguments[keys]===undefined){
           throw new Error('参数不够')
       }
      })
    //   console.log(arguments)
    return method.apply(this,arguments)
    }
// 取得数据

}
// 先执行参数装饰器后执行方法装饰器
class User{
    @valDecorator
    find(@RequiredDecorator name:string, @RequiredDecorator id:number){}
}
new User().find('qql',1)

TypeScript

1.ts中使用Promise

interface ResItf{
    code:number
    data:{a:number,b:number}[]
    message:string
}

let  p:Promise<ResItf>=new Promise((resolve,reject)=>{
    resolve({
        code:0,
        data:[{a:1,b:2},{a:11,b:22}],
        message:''
    })
})
p.then(res=>{
    if(res.code===0){
        res.data.map(item=>item.a)
    }
})

2.ts函数中的this

export{}
type objType={
    A:string,
    B:(m:string)=>void
}
let obj:objType={
    A:'',
    B:()=>{}
}
// this的类型必须和调用类型一致
function B<T extends objType>(this:T ,C:string){
    this.A=C
}
obj.B=B<objType>

3.ts的工具类型Partial

interface A{
    name:string
    age:number
}
/**
 * 缺省工具类型
 * Partial<A>{name?:string|undefined,age?:string|undefined}
 *  type Partial<T> = { [P in keyof T]?: T[P];
};
 */
let obj:Partial<A>={
    name:''
}

4.ts工具类型Required

export{}
interface A{
    name?:string
    age?:number
}
/**
 * 不可缺省工具类型
 * Required<A>{name:string,age:string}
 *  type  = { [P in keyof T]-?: T[P];
};
};
 */
let obj:Required<A>={
    name:'',
    age:1
}

5.ts中的keyof和in

export{}
interface A{
    name:string
    age:number
    [idx:number]:number
}
// keyof后面跟接口,标识接口的属性名之一
type a=keyof A
let p:a
// p的接口结果限制 p:string|number
p='name'
p='age'
p=1



type StrOrNum=string|number
type PItf={
    [k in StrOrNum]:string //[k in StrOrNum] 表示类型可以是数子也可以是字符串
}
let obj:PItf={
    a:'',
    10:''
}
//  typeof提取变量或对象类型

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值