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

时间:2017-03-13 13:05:00

标签: 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。有没有办法用本机实现或TypeScript解决这个问题?

1 个答案:

答案 0 :(得分:4)

您可以将“HTMLElement(document.getElementById("descriptionField") as HTMLInputElement).select(); “压缩”为a type which has the select method

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

或:

// from Outlook .msg
Email email =             EmailConverter.outlookMsgToEmail(readToString("yourMessage.msg"));
Email email =             EmailConverter.outlookMsgToEmail(new File("yourMessage.msg"));
Email email =             EmailConverter.outlookMsgToEmail(getInputStream("yourMessage.msg"));
String eml =              EmailConverter.outlookMsgToEML(readToString("yourMessage.msg"));
String eml =              EmailConverter.outlookMsgToEML(new File("yourMessage.msg"));
String eml =              EmailConverter.outlookMsgToEML(getInputStream("yourMessage.msg"));
MimeMessage mimeMessage = EmailConverter.outlookMsgToMimeMessage(readToString("yourMessage.msg"));
MimeMessage mimeMessage = EmailConverter.outlookMsgToMimeMessage(new File("yourMessage.msg"));
MimeMessage mimeMessage = EmailConverter.outlookMsgToMimeMessage(getInputStream("yourMessage.msg"));

这基本上告诉编译器“别担心,我知道这里预期的类型。”,在TypeScript中被称为 Type Assertions 。< / p>

它不会影响运行时,只需让编译器放心,这样就不会有任何抱怨。