要解决该错误,需明确指定元素类型为 HTMLInputElement,因为 select() 方法属于输入元素。
步骤解释:
-
类型断言:使用
as HTMLInputElement将元素类型断言为输入元素。 -
可选链操作符:保持
?.避免元素为null时出错。
typescript
// 选中内容
let element = document.getElementById("password") as HTMLInputElement;
element?.select();
或单行写法:
typescript
(document.getElementById("password") as HTMLInputElement)?.select();
补充建议:
-
若不确定元素类型,可用
instanceof进行类型检查:
typescript
const element = document.getElementById("password");
if (element instanceof HTMLInputElement) {element.select();
}
通过类型断言或类型检查,TypeScript 就能正确识别 select() 方法,消除错误。