javascript - "TS2339: Property ... does not exist on type ...", 在输入字段

标签 javascript angular typescript

我有一个输入字段,当用户单击某个按钮时,它需要获得焦点并完全选择其文本值(这样当用户键入时,他们会替换整个值)。

这是输入字段的标记:

<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/

相关文章:

javascript - 我怎么知道哪些处理程序在 promise 中抛出错误?

css - Angular - 带滚动条的 slider

typescript - 什么是 typescript `--lib` 库文件?

Angular 2在构造函数外注入(inject)依赖

playframework - Play 中的 TypeScript 模块解析是如何工作的?

import - 忽略 typescript 上的 "cannot find module"错误

javascript - 在多个 angular.js 应用程序之间共享单个服务

javascript - 单击时使导航栏折叠/关闭

javascript - 使用 JavaScript 使用 QuickTime 录制屏幕的自动化脚本

javascript - angular2如何区分组件 View 中的Light DOM或Shadow DOM