TypeScript错误:获取input值时提示属性'value'在类型'HTMLElement'上不存在
大家好!我刚开始学习TypeScript,遇到了一个非常奇怪的错误,无法理解。
我有一个简单的HTML代码,包含一个输入框和一个按钮:
```html
```
在TypeScript文件中,我想在点击按钮时获取input的值:
```typescript
const input = document.getElementById('username');
const button = document.getElementById('btn');
button.addEventListener('click', () => {
const name = input.value; // 错误!
console.log(name);
});
```
但TypeScript报错:
**"Property 'value' does not exist on type 'HTMLElement'."**
我已经检查过了——HTML中确实存在id为'username'的元素。在普通JavaScript中,这样的代码运行没有问题。为什么TypeScript会报错?如何正确获取input的值?我尝试过显式指定类型,但不确定是否正确。
请告诉我如何修复这个错误。