TypeScript不能读取属性addEventListener



我正在学习TypeScript我正在跟随一个youtube教程,一步一步地做。但由于某些原因,我仍然收到一个错误。

Uncaught TypeError: Cannot read property 'addEventListener' of null

我重写了代码两次,我仍然收到相同的错误。你们能不能帮我弄清楚到底是怎么回事?

我还是个新手,但这快把我逼疯了。

谢谢。

//Interface
interface PersonObjInterface{
name: string,
age: number
}
//Interface for Obj
let objPerson: PersonObjInterface = {
name: "John Doe",
age: 40
}
//Interface for Class
class ClassPerson implements PersonObjInterface{
constructor(public name: string, public age: number){}
greet(){
return `Hi, my name is ${this.name} and I am ${this.age} yo.`
}
}
//let John = new ClassPerson("John", 40)
//console.log(John.greet());
//DOM
const inputName = document.querySelector('#name') as HTMLInputElement
const inputAge = document.querySelector('#age') as HTMLInputElement
const inputForm = document.querySelector('form')!
const greeting = document.querySelector('.greeting') as HTMLDivElement
inputForm.addEventListener('submit', (e) => {
e.preventDefault()
const person = new ClassPerson(inputName.value, inputAge.valueAsNumber)
greeting.innerText = person.greet()
inputForm.reset()
})

html

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="app.js"></script>
<title>TypeScript Crash Course</title>
</head>
<body>
<form>
<input type="text" name="name" id="name" />
<input type="number" name="age" id="age" />
<input type="submit" value="Say hi" />
</form>
<div class="greeting"></div>
</body>

您正在加载您的app.js在您的html文档的标题。此时,没有<body><form>,因为DOM尚未完全加载。所以你所有的document.querySelector()调用将返回null

最简单的解决方案是在HTML文档的末尾加载脚本,这样所有的DOM元素都已经存在了。
<html>
<head>
...
</head>
<body>
...
<script src="app.js"></script>  <!-- move script loading from head to here -->
</body>
</html>

作为另一种选择,您还可以在加载脚本时使用defer属性,它将只在页面加载后执行脚本,而不管script标记放置在何处。但这只适用于外部脚本通过src=...属性加载。

<html>
<head>
<script src="app.js" defer></script> 
...
</head>
<body>
...
</body>
</html>