0

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.

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

4 Comments

That could be true. But I can't figure out how to define a function and set its type at the same time.
const validatePass1: Validator = function(rule, value, callback) { ... } should work.
Oops, duh. Brain fart. Lemme try that.
Got it! I've been staring at TS failures too long. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.