1 html

1 defer 属性
script 标签写在 head 标签内,需要使用 defer 属性,延迟执行,否则会无法获取到对应 dom
或者不写defer ,将 script 标签写在 body 标签内
2 浏览器支持 .js 文件,而不支持 .ts 文件,因此 src

  1. <head>
  2. // defer 属性
  3. <script src='using-ts.js' defer></script>
  4. </head>
  5. <body>
  6. <input type='number' id='num1' placeholder='Number1'/>
  7. <input type='number' id='num2' placeholder='Number2'/>
  8. <button>Add!</button>
  9. </body>

2 js

  1. const button = ducument.querySelector('button')
  2. const input1 = document.getElementById('num1')
  3. const input2 = document.getElementById('num2')
  4. function add(num1, num2) {
  5. if(typeof num1 === number && typeof num2 === number) {
  6. return num1 + num2
  7. } else {
  8. return +num1 + +num2
  9. }
  10. }
  11. button.addEventListener('click', function() {
  12. console.log(add(input1.value, input2.value))
  13. })
  14. ---------------------------------------------------
  15. function add(num1, num2) {
  16. if(typeof num1 !== 'number' || typeof num2 !== 'number') {
  17. throw new Error('Incorrect input!')
  18. }
  19. return num1 + num2
  20. }
  21. const number1 = '5';
  22. const number2 = 2.8
  23. const result = add(number1, number2)
  24. console.log(result)

3 ts

1 ! 表示不为空值
2 as HTMLInputElement ts 类型

  1. const button = document.querySelector('button')
  2. const input1 = document.getElementById('num1')! as HTMLInputElement
  3. const input2 = document.getElementById('num2')! as HTMLInputElement
  4. function add(num1: number, num2: number) {
  5. return num1 + num2
  6. }
  7. button.addEventListener('click', function() {
  8. console.log(add(+input1.value, +input2.value))
  9. })