この記事では、TypeScriptを使ってシンプルなTodoリストアプリを作成する方法を説明します。
まずは、以下のものを準備しましょう。
それでは、プロジェクトを作成していきます。まずはターミナル(コマンドプロンプト)を開きましょう。
適当な場所に新しいフォルダーを作成します。以下のコマンドを入力して新しいフォルダーを作りましょう。
mkdir todo-app
cd todo-app
次に、TypeScriptをインストールします。以下のコマンドを実行してください。
npm install typescript --save-dev
TypeScriptの設定ファイル(tsconfig.json)を作成します。以下のコマンドを実行します。
npx tsc --init
これで設定ファイルが生成されますが、特に設定を変更する必要はありません。
それでは、Todoリストアプリのコードを書いていきます。
プロジェクトフォルダー内に「index.html」というファイルを作成し、以下のコードを入力してください。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Todoリストアプリ</title>
<script src="script.js" defer></script>
</head>
<body>
<h1>Todoリスト</h1>
<input type="text" id="todo-input" placeholder="Todoを追加">
<button id="add-button">追加</button>
<ul id="todo-list"></ul>
</body>
</html>
次に、プロジェクトフォルダーに「script.ts」というファイルを作成し、以下のコードを入力します。
const input = document.getElementById('todo-input') as HTMLInputElement;
const button = document.getElementById('add-button') as HTMLButtonElement;
const todoList = document.getElementById('todo-list') as HTMLUListElement;
button.addEventListener('click', () => {
if (input.value.trim() !== '') {
const listItem = document.createElement('li');
listItem.textContent = input.value;
todoList.appendChild(listItem);
input.value = '';
}
});
作成したTypeScriptファイルをJavaScriptにコンパイルします。以下のコマンドを実行してください。
npx tsc script.ts
これでTodoリストアプリの準備が整いました。ブラウザで「index.html」を開いて、Todoを追加してみてください。