typescript - 函数类型设置'this'上下文,不起作用
问题描述
我的 Vue 组件中有以下代码:
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({
// ...
这不像记录的那样工作。validatePass1
我在func中收到类型错误:
'this' implicitly has type 'any' because it does not have a type annotation.
我不明白为什么这不起作用。
解决方案
validatePass1
需要用function
关键字而不是箭头函数来定义。箭头函数忽略this
调用时传递的(这是您的类型注释所在),并始终使用this
定义它的位置,在这种情况下是全局对象(我认为)。
推荐阅读
- python - 带有情节的线序
- visual-studio-code - 如何创建提示窗口以显示 gif 并在几秒钟后关闭窗口?
- angular - 启用内容编码:gzip 用于 angular(7) Web 应用程序中的生产构建?
- svelte - 如何在 Svelte 中设置事件的全局样式
- sql - 在一行中查询多个事务
- android - 类的协程单元测试失败
- typescript - 带有 *ngFor 的 ng-template 问题在 Angular 8
- c++ - 如何计算字符串并将其存储在变量中?
- java - 程序切片插件 Indus 和 kaveri 在 eclipse 中是如何工作的?
- php - 在 CodeIgniter 文件上传中设置最大大小