我有一个输入字段,当用户单击某个按钮时,它需要获得焦点并完全选择其文本值(这样当用户键入时,他们会替换整个值)。
这是输入字段的标记:
<input type="text" id="descriptionField" class="form-control">
...以及负责焦点/选择的函数:
public copy(): void {
document.getElementById("descriptionField").focus();
document.getElementById("descriptionField").select();
}
.focus()
工作正常,但 .select()
抛出错误:
TS2339: Property 'select' does not exist on type 'HTMLElement'.
我曾尝试寻找解决方案,但其中大部分都依赖于 jQuery。有什么方法可以通过 native 实现或 TypeScript 来解决这个问题吗?
最佳答案
您可以将 HTMLElement
“类型转换”为 a type which has the select
method :
(document.getElementById("descriptionField") as HTMLInputElement).select();
或:
(<HTMLInputElement>document.getElementById("descriptionField")).select();
这基本上告诉编译器“别担心,我知道这里需要什么类型。”,并且被称为 Type Assertions 在 TypeScript 中。
它不会影响运行时,只是让编译器放心,所以它不会有任何可提示的。
关于javascript - "TS2339: Property ... does not exist on type ...", 在输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42764404/