this类型
- TypeScript可推导的this类型
-
- this相关的内置工具
- 类型转换
- ThisParameterType<>
- ThisParameterType<>
- ThisType
TypeScript可推导的this类型
函数中this默认类型
对象中的函数中的this
| |
| const obj ={ |
| a:1, |
| b:2, |
| fun:function(){ |
| |
| console.log(this.a) |
| } |
| } |
| obj.fun() |
复制
明确this指向
- 步骤1:tsc --init,生成文件

- 步骤二,打开注释
- 不让有模糊的this,必须指定this指向

- this就会更严格,这个是this根据上下文自行推导出来的类型

- 这个是没有上下文。推导不出来的,在严格模式下,不允许模糊this,所以会报错

怎么指定this类型
- 函数的第一个参数我们可以根据该函数之后被调用的情况,用于声明this的类型,名词必须叫this
- 在后续调用函数传入参数的时候。从第二个参数开始传递,this参数会在编译后被抹除
| |
| function fun( this:{name:string},info:{name:string}){ |
| console.log(this) |
| } |
| |
| 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 |
| |
| type thisType= ThisParameterType<funtype> |
| |
| type thisRemove= OmitThisParameter<funtype> |
| |
| export{} |
复制
ThisType
| |
| type User = { |
| name: string |
| age: number |
| } |
| type Intype = { |
| User: User |
| getname: () => void |
| getage: () => void |
| } |
| const username: Intype = { |
| User: { |
| name: "乞力马扎罗", |
| age: 18 |
| }, |
| |
| getname: function (this:User) { |
| console.log(this.name) |
| }, |
| getage: function (this:User) { |
| console.log(this.age) |
| } |
| |
| } |
| |
| |
| |
| username.getname.call(username.User) |
| username.getage.call(username.User) |
| export { } |
复制
| type User = { |
| name: string |
| age: number |
| } |
| type Intype = { |
| User: User |
| getname: () => void |
| getage: () => void |
| } |
| |
| const username: Intype & ThisType<User> = { |
| User: { |
| name: "乞力马扎罗", |
| age: 18 |
| }, |
| |
| getname: function () { |
| console.log(this.name) |
| }, |
| getage: function () { |
| console.log(this.age) |
| } |
| |
| } |
| |
| |
| |
| username.getname.call(username.User) |
| username.getage.call(username.User) |
| export { } |
复制