简体   繁体   English

输入字段上的“TS2339:属性...在类型...上不存在”

[英]“TS2339: Property … does not exist on type …”, on input field

I have an input field which, when a user clicks a certain button, needs to be focused and have its text value selected entirely (that way when users type, they replace the entire value). 我有一个输入字段,当用户点击某个按钮时,需要对其进行聚焦并完全选择其文本值(当用户键入时,它们会替换整个值)。

Here's the input field's markup: 这是输入字段的标记:

<input type="text" id="descriptionField" class="form-control">

...and the function responsible for focus/select: ......以及负责聚焦/选择的功能:

public copy(): void {
    document.getElementById("descriptionField").focus();
    document.getElementById("descriptionField").select();
}

.focus() works fine, but .select() throws an error: .focus()工作正常,但.select()会抛出错误:

TS2339: Property 'select' does not exist on type 'HTMLElement'.

I've tried looking for solutions but most of them rely on jQuery. 我试过寻找解决方案,但大多数都依赖于jQuery。 Is there any way to solve this with native implementation, or with TypeScript? 有没有办法通过本机实现或TypeScript来解决这个问题?

You can "type-cast" the HTMLElement to a type which has the select method : 您可以将HTMLElement “类型转换”为具有select方法的类型

(document.getElementById("descriptionField") as HTMLInputElement).select();

or: 要么:

(<HTMLInputElement>document.getElementById("descriptionField")).select();

This basically tells the compiler "don't worry, I know what type is expected here." 这基本上告诉编译器“不要担心,我知道这里预期的类型。” , and is called Type Assertions in TypeScript. ,在TypeScript中称为Type Assertions

It does not affect the runtime, just reassures the compiler so it won't have anything to complain about. 它不会影响运行时,只是让编译器放心,因此它不会有任何抱怨。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM