0%

ThisType

在对象字面量方法中的this类型,将由以下决定:

如果这个方法显示指定了this参数,那么this具有该参数的类型

1
2
3
4
5
6
let bar = {
x: "hello",
f(this:{ message: string }){
this;//{message: string}
}
}

否则,如果方法由带this参数的签名进行上下文键入,那么this具有该参数的类型

1
2
3
4
5
6
let foo = {
x: "hello",
f(n: number) {
this;//{x:string,f(n: number): void}
}
}

如果–noImplicityThis选项启用,并且对象字面量中包含由ThisType键入的上下文类型,那么this的类型为T

如果–noImplicityThis选项启用,并且对象字面量中包含由ThisType键入的上下文类型,那么this的类型为该上下文类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
type ObjectDescriptor<D,M> = {
data?: D;
methods?: M & ThisType<D&M>//Type of 'this' is D&M
}
function makeObject<D,M>(desc:ObjectDescriptor<D,M>:D & M) {
let data: object = desc.data || {}
let methods: object = desc.methods || {}
return {...data,...methods} as D&M;
}
let obj = makeObject({
data: {x:0,y:0},
methods: {
moveBy(dx:number,dy:number) {
this.x+=dx;//Strongly typed this
this.y+=dy;//Strongly typed this
}
}
})
obj.x=10;
obj.y=20;
obj.moveBy(5,5);

否则,如果 --noImplicitThis 选项已经启用,this 具有该对象字面量的类型。

否则,this 的类型为 any