网站重复,重庆网站建设哪家好,wordpress 登陆 没反应,网站建设seo优化培训this类型 TypeScript可推导的this类型函数中this默认类型对象中的函数中的this明确this指向 怎么指定this类型 this相关的内置工具类型转换ThisParameterTypeThisParameterTypeThisType TypeScript可推导的this类型
函数中this默认类型
对象中的函数中的this… this类型 TypeScript可推导的this类型函数中this默认类型对象中的函数中的this明确this指向 怎么指定this类型 this相关的内置工具类型转换ThisParameterTypeThisParameterTypeThisType TypeScript可推导的this类型
函数中this默认类型
对象中的函数中的this
// 对象中的this
const obj {a:1,b:2,fun:function(){//默认情况下this是any类型console.log(this.a)}
}
obj.fun()//1明确this指向
步骤1tsc --init生成文件 步骤二打开注释不让有模糊的this必须指定this指向 this就会更严格这个是this根据上下文自行推导出来的类型 这个是没有上下文。推导不出来的在严格模式下不允许模糊this所以会报错
怎么指定this类型
函数的第一个参数我们可以根据该函数之后被调用的情况用于声明this的类型名词必须叫this在后续调用函数传入参数的时候。从第二个参数开始传递this参数会在编译后被抹除
// - 把this作为函数的第一个参数给指定类型
function fun( this:{name:string},info:{name:string}){console.log(this)//{ name: 名字 }
}
//调用的时候得这样调用不然会报void类型的错误
fun.call({name:名字},{name:第二个名字})this相关的内置工具
类型转换
TS提供了一些工具来辅助进行常见的类型转换这些类型全局可用
ThisParameterType
用于提取一个函数类型Type的this没有this则返回unknown
ThisParameterType
想要移除一个函数类型type的this参数类型并且返回当前的函数类型
function fun( this:{name:string},info:{name:string}){console.log(this)
}
//获取函数的类型
type funtype typeof fun
//想要直接获取函数的this类型,采用内置组件
type thisType ThisParameterTypefuntype
//想要移除一个函数类型type的this参数类型并且返回当前剩余的函数类型
type thisRemove OmitThisParameterfuntypeexport{}ThisType
被用作标记一个上下文的this类型原始方法
//原始获取this繁琐
type User {name: stringage: number
}
type Intype {User: Usergetname: () voidgetage: () void
}
const username: Intype {User: {name: 乞力马扎罗,age: 18},//ts接收指定的this指向getname: function (this:User) {console.log(this.name)//乞力马扎罗},getage: function (this:User) {console.log(this.age)//18}}
//call() 可以修改函数调用时 this 的指向其余参数则会作为原函数的参数。
//第一个参数 thisArg。代表 this 将会被指向的值。如果不是对象也会通过 Object() 方法转换为对象。如果是 null 或 undefinedthis 则会指向全局对象即 window 或 global
//传入this指向
username.getname.call(username.User)
username.getage.call(username.User)
export { }采取ThisType
type User {name: stringage: number
}
type Intype {User: Usergetname: () voidgetage: () void
}
//通过ThisTypeUser,将这里以后不管多少函数this的指向始终是User
const username: Intype ThisTypeUser {User: {name: 乞力马扎罗,age: 18},//ts接收指定的this指向getname: function () {console.log(this.name)//乞力马扎罗},getage: function () {console.log(this.age)//18}}
//call() 可以修改函数调用时 this 的指向其余参数则会作为原函数的参数。
//第一个参数 thisArg。代表 this 将会被指向的值。如果不是对象也会通过 Object() 方法转换为对象。如果是 null 或 undefinedthis 则会指向全局对象即 window 或 global
//传入this指向
username.getname.call(username.User)
username.getage.call(username.User)
export { }