Akcore
Akcore

Reputation: 149

JS/TS Difference bewteen function definitions in object?

A specific problem fixed was one of function declaration mismatch. I am wondering, in my specific case, what the difference between

const obj => {
  thing1: () => void //This is type thing1: () => undefined
  thing2(){ return; }  //This is type  thing2(): void
};

I do not see any difference between the two. One is an object attribute that contains a lambda function and the other is a function declared in the object. Why are they different types?

Upvotes: 1

Views: 48

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187014

Your example code is invalid, but I'm going to assume your meant this:

const obj = {
  thing1: () => undefined,
  thing2() { return },
};

The type of thing1 is:

(property) thing1: () => undefined

This is a property of obj that has a value of a function. That function is an arrow function that returns undefined. Arrow functions capture the value of this from the declaring scope. So this could be anything, from the type only can't tell. However, what this does tell you is that you don't need to be concerned with the value of this since it's bound in the function declaration itself. This means you could break it off and pass it as a callback like:

obj.thing1() // `this` is whatever `this` was when the function was declared.

const fn = obj.thing1
fn() // `this` is whatever `this` was when the function was declared.

thing2 is typed as:

(method) thing2(): void

In this case thing2 is a method of obj that returns a value that should not be used. In reality it's undefined, but as far as type is concerned, it returns an unusable return value.

And here this is not bound for you, and is instead set by calling syntax:

obj.thing2()
// ^ this dot sets the value of `this` in `thing2()`.

If you were to do the same test above here:

obj.thing2() // `this` is `obj`

const fn = obj.thing2
fn() // `this` the global object, which is probably not good.

Upvotes: 1

Related Questions