类型"EventTarget"上不存在属性“值" [英] Property 'value' does not exist on type 'EventTarget'
问题描述
我将TypeScript版本2用于Angular 2组件代码.
I am using TypeScript Version 2 for an Angular 2 component code.
对于以下代码,我遇到错误类型'EventTarget'上不存在属性'值'",这可能是解决方案.谢谢!
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)|| []).length
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"上不存在属性“值"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!