Reputation: 3856
I have a function call like this:
var myVar = myFunction({
property: 'prop',
functionProperty() {
console.log(this.property);
},
functionProperty2() {
this.functionProperty();
}
});
Is there any way to add typings to the object you are passing to the function without declaring it first?
And another question, is there a way to make this.functionProperty() know that this refers to the object? Working with VSCode when hovering it doesn't recognize the keyword this as the object.
Upvotes: 1
Views: 93
Reputation: 249466
If you use the compiler option noImplicitThis
then this
will be typed inside your object literal functions correctly.
function myFunction<T>(o: T) {
}
var myVar = myFunction({
property: 'prop',
functionProperty() {
console.log(this.property);
},
functionProperty2() {
this.functionProperty();
this.missing // error
}
});
If you need more control over the type of this
, you can use ThisType
which is a special marker for the compiler and will tell the compiler what the type of this
will be inside the object literal functions (but this will also require noImplicitAny
).
function myFunction<T>(o: T & ThisType<T & { extra: boolean }>) {
}
var myVar = myFunction({
property: 'prop',
functionProperty() {
console.log(this.property);
},
functionProperty2() {
this.functionProperty();
this.missing // error
this.extra //ok
}
});
Upvotes: 1