🍣
TypeScript環境を簡単に作ろう
まずはindex.htmlを作っておきます
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Understanding TypeScript</title>
<script src="using-ts.js" defer></script>
</head>
<body>
<input type="number" id="num1" placeholder="Number 1" />
<input type="number" id="num2" placeholder="Number 2" />
<button>Add!</button>
</body>
</html>
typescriptをインストールします
npm init
npmt i -D typescript
次は、using-ts.tsというファイルを作ります
using-ts.ts
const button = document.querySelector("button")!;
const input1 = document.getElementById("num1")! as HTMLInputElement;
const input2 = document.getElementById("num2")! as HTMLInputElement;
function add(num1: number, num2: number) {
return num1 + num2;
}
button.addEventListener("click", function() {
console.log(add(+input1.value, +input2.value));
});
Compileのコマンドを打ちます
npx tsc using-ts.ts
usingts.jsというファイルが生成され、index.htmlに使えるようになりました
Discussion