类型“EventTarget"上不存在属性“value" [英] Property 'value' does not exist on type 'EventTarget'

查看:68
本文介绍了类型“EventTarget"上不存在属性“value"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 TypeScript 版本 2 用于 Angular 2 组件代码.

I am using TypeScript Version 2 for an Angular 2 component code.

我收到错误类型 'EventTarget' 上不存在属性 'value'";对于下面的代码,可能的解决方案是什么.谢谢!

I am getting error "Property 'value' does not exist on type 'EventTarget'" for below code, what could be the solution. Thanks!

e.target.value.match(/S+/g) ||[]).长度

import { Component, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'text-editor',
  template: `
    <textarea (keyup)="emitWordCount($event)"></textarea>
  `
})
export class TextEditorComponent {
  @Output() countUpdate = new EventEmitter<number>();

  emitWordCount(e: Event) {
    this.countUpdate.emit(
            (e.target.value.match(/S+/g) || []).length);
  }
}

推荐答案

你需要明确地告诉 TypeScript 你的目标 HTMLElement 的类型.

You need to explicitly tell TypeScript the type of the HTMLElement which is your target.

这样做的方法是使用泛型类型将其强制转换为正确的类型:

The way to do it is using a generic type to cast it to a proper type:

this.countUpdate.emit((<HTMLTextAreaElement>e.target).value./*...*/)

或(如你所愿)

this.countUpdate.emit((e.target as HTMLTextAreaElement).value./*...*/)

或(再次,偏好问题)

const target = e.target as HTMLTextAreaElement;

this.countUpdate.emit(target.value./*...*/)

这会让 TypeScript 知道该元素是一个 textarea 并且它会知道 value 属性.

This will let TypeScript know that the element is a textarea and it will know of the value property.

对于任何类型的 HTML 元素都可以做到这一点,只要您向 TypeScript 提供更多有关其类型的信息,它就会以适当的提示和当然更少的错误回报您.

The same could be done with any kind of HTML element, whenever you give TypeScript a bit more information about their types it pays you back with proper hints and of course less errors.

为了方便以后使用,您可能需要直接定义具有目标类型的事件:

To make it easier for the future you might want to directly define an event with the type of its target:

// create a new type HTMLElementEvent that has a target of type you pass
// type T must be a HTMLElement (e.g. HTMLTextAreaElement extends HTMLElement)
type HTMLElementEvent<T extends HTMLElement> = Event & {
  target: T; 
  // probably you might want to add the currentTarget as well
  // currentTarget: T;
}

// use it instead of Event
let e: HTMLElementEvent<HTMLTextAreaElement>;

console.log(e.target.value);

// or in the context of the given example
emitWordCount(e: HTMLElementEvent<HTMLTextAreaElement>) {
  this.countUpdate.emit(e.target.value);
}

这篇关于类型“EventTarget"上不存在属性“value"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆