ffxsam
ffxsam

Reputation: 27713

Function type setting 'this' context, not working

I have the following code in my Vue component:

import Vue from 'vue';
import { ElForm } from 'element-ui/types/form';

type Validator = (
  this: typeof PasswordReset,
  rule: any,
  value: any,
  callback: (error?: Error) => void
) => void;

const validatePass1: Validator = (rule, value, callback) => {
  if (value && this.form.passwordConfirm) {
    (this.$refs.form as ElForm).validateField('passwordConfirm', valid => {});
  }
};
// ...

const PasswordReset = Vue.extend({
  // ...

This is not working as documented. I get a type error in the validatePass1 func:

'this' implicitly has type 'any' because it does not have a type annotation.

I don't understand why this isn't working.

Upvotes: 0

Views: 60

Answers (1)

Matt McCutchen
Matt McCutchen

Reputation: 30879

validatePass1 needs to be defined with the function keyword instead of as an arrow function. An arrow function ignores the this passed at the time of the call (which is what your type annotation is on) and always uses the this from where it was defined, which in this case is the global object (I think).

Upvotes: 1

Related Questions