dwjohnston
dwjohnston

Reputation: 11813

Type definition for a function that has a particular 'this' object

I want to create a series of objects that look like this:


type MyThing<T> = {
    data: T; 
    fn: ???;
}

const foo = {
    data: {
       foo: "bar"
    }, 
    fn: function() {
       return `Hello ${this.data.foo}!`; 
    }
}

In order for this to work, you must use the long form function syntax and not an arrow function.

How would I type this function such that it would cause an error if someone were to use an arrow function?

Upvotes: 0

Views: 65

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187034

You type the this arg with the special this: SomeType argument.

Read more about the this parameter here in the docs.

type MyThing<T> = {
    data: T; 
    fn: (this: MyThing<T>) => void;
}

const foo = {
    data: {
       foo: "bar"
    }, 
    fn: () => {
       return `Hello ${this.data.foo}!`; 
       // The containing arrow function captures the global value of 'this'.(7041)
       // Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.(7017)
    }
}

Playground

Upvotes: 2

Related Questions