You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
What people usually _intend_ when writing `index?` as an optional parameter is that they want both of these calls to be legal:
381
+
What people usually intend when writing `index?` as an optional parameter is that they want both of these calls to be legal:
382
382
383
383
```ts twoslash
384
384
// @errors: 2532
@@ -538,6 +538,58 @@ Callers can invoke this with either sort of value, and as an added bonus, we don
538
538
539
539
> Always prefer parameters with union types instead of overloads when possible
540
540
541
+
### Declaring `this` in a Function
542
+
543
+
TypeScript will infer what the `this` function should be in a function via code flow analysis, for example in the following:
544
+
545
+
```ts twoslash
546
+
const user = {
547
+
id: 123,
548
+
549
+
admin: false,
550
+
becomeAdmin: function () {
551
+
this.admin=true;
552
+
},
553
+
};
554
+
```
555
+
556
+
TypeScript understands that the function `user.becomeAdmin` has a corresponding `this` which is the outer object `user`. `this`, _heh_, can be enough for a lot of cases, but there are a lot of cases where you need more control over what object `this` represents. The JavaScript specification states that you cannot have a parameter called `this`, and so TypeScript uses that syntax space to let you declare the type for `this` in the function body.
This pattern is common with callback-style APIs, where another object typically controls when your function is called. Note that you need to use `function` and not arrow functions to get this behavior:
Copy file name to clipboardexpand all lines: packages/documentation/copy/en/handbook-v2/Object Types.md
+2-2
Original file line number
Diff line number
Diff line change
@@ -873,7 +873,7 @@ distanceFromOrigin(point);
873
873
Here, `distanceFromOrigin` never modifies its elements, but expects a mutable tuple.
874
874
Since `point`'s type was inferred as `readonly [3, 4]`, it won't be compatible with `[number, number]` since that type can't guarantee `point`'s elements won't be mutated.
875
875
876
-
## Other Kinds of Object Members
876
+
<!--## Other Kinds of Object Members
877
877
878
878
Most of the declarations in object types:
879
879
@@ -883,4 +883,4 @@ Most of the declarations in object types:
0 commit comments