1

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.

1 Answer 1

1

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
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! It worked. Do you know any way to declare the property's type?
What property? Of an object literal? Unless you want to specify the whole type of the object literal, the simplest option is to use a type assertion to the desired type { p: null as number}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.