質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.31%
TypeScript

TypeScriptは、マイクロソフトによって開発された フリーでオープンソースのプログラミング言語です。 TypeScriptは、JavaScriptの構文の拡張であるので、既存の JavaScriptのコードにわずかな修正を加えれば動作します。

Q&A

解決済

1回答

272閲覧

TypeScriptのincludesでエラーが出てしまう

jimunomado

総合スコア20

TypeScript

TypeScriptは、マイクロソフトによって開発された フリーでオープンソースのプログラミング言語です。 TypeScriptは、JavaScriptの構文の拡張であるので、既存の JavaScriptのコードにわずかな修正を加えれば動作します。

1グッド

0クリップ

投稿2025/03/07 07:45

編集2025/03/07 08:20

実現したいこと

今百人一首の下の句を覚えるアプリを作成しています。
純粋にクイズをやる部分と、復習パート(クイズ部分に☆マークを付け、それが押下されたものを復習パートに持っていく)に別れています。

発生している問題・分からないこと

復習対象にマークを付ける機能、そして、マークの表示更新のincludesのところでエラーが発生しています。

エラーメッセージ

error

1app.ts:20:35 - error TS2550: Property 'includes' does not exist on type 'number[]'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2016' or later. 220 isFavorite: favorites.includes(k.number) // お気に入りフラグを設定 3app.ts:101:19 - error TS2550: Property 'includes' does not exist on type 'number[]'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2016' or later. 4101 if (favorites.includes(currentKaruta.number)) {

該当のソースコード

TypeScript

1// ページ読み込み時にJSONデータを取得 2fetch('karuta.json') 3 .then(response => response.json()) 4 .then((data: Karuta[]) => { 5 karutaList = data.map(k => ({ 6 ...k, 7 isFavorite: favorites.includes(k.number) // お気に入りフラグを設定 8 })); 9 nextQuestion(); 10 }); 11 12function updateFavoriteButton() { 13 const favoriteButton = document.getElementById('favoriteButton')!; 14 if (!currentKaruta) return; 15 16 if (favorites.includes(currentKaruta.number)) { 17 favoriteButton.textContent = '★'; 18 favoriteButton.style.color = 'gold'; 19 } else { 20 favoriteButton.textContent = '☆'; 21 favoriteButton.style.color = 'gray'; 22 } 23}

試したこと・調べたこと

  • teratailやGoogle等で検索した
  • ソースコードを自分なりに変更した
  • 知人に聞いた
  • その他
上記の詳細・結果

moduleとlibのバージョンの問題であることが読み取れたため、tsconfig.jsonをES2020に修正していますが、それでもエラーが出続けます。
それともmoduleとlibのバージョンの問題ではないのでしょうか?どなたかお知恵を拝借願いたいです。

補足

TypeScriptのバージョン

  • 5.8.2

Node.jsのバージョン

  • 18.14.0
maisumakun👍を押しています

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

maisumakun

2025/03/07 10:46

TypeScriptのコンパイル環境は、どのような方法で構築・実行していますか?
jimunomado

2025/03/07 10:55

コンパイル環境はvscode上で行っており、ターミナルからコマンドを打っております。
maisumakun

2025/03/07 14:02

tsconfig.jsonの内容と、入力したコマンドも示していただけませんでしょうか。
jimunomado

2025/03/08 02:24

jsonの内容は以下です(コメントアウトされているものは除いて掲載しています) ```json { "compilerOptions": { "target": "ES2020", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ "lib": [ "ES2020", "DOM" ], "module": "ESNext", /* Specify what module code is generated. */ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ /* Type Checking */ "strict": true, /* Enable all strict type-checking options. */ "skipLibCheck": true /* Skip type checking all .d.ts files. */ } } ``` また入力コマンドは `tsc app.ts`です。
guest

回答1

0

自己解決

皆様から様々なご提案をいただいた中申し訳ないのですが、includesを使わない方法に変更しました。。

TypeScript

1type Karuta = { 2 number: number; 3 upper: string; 4 lower: string; 5}; 6 7let karutaList: Karuta[] = []; 8let currentKaruta: Karuta | null = null; 9let favoriteList: number[] = loadFavorites(); 10let correctCount = 0; 11let totalCount = 0; 12 13// JSONデータを読み込む 14fetch('karuta.json') 15 .then(response => response.json()) 16 .then((data: Karuta[]) => { 17 karutaList = data; 18 nextQuestion(); 19 }); 20 21function nextQuestion() { 22 const upperText = document.getElementById('upperText')!; 23 const choicesDiv = document.getElementById('choices')!; 24 const result = document.getElementById('result')!; 25 const nextButton = document.getElementById('nextButton')!; 26 const favoriteButton = document.getElementById('favoriteButton')!; 27 28 result.textContent = ''; 29 choicesDiv.innerHTML = ''; 30 31 // ランダムに1首選ぶ 32 if (karutaList.length === 0) return; 33 currentKaruta = karutaList[Math.floor(Math.random() * karutaList.length)]; 34 35 // `null` でないことを保証 36 if (!currentKaruta) return; 37 38 upperText.textContent = currentKaruta.upper; 39 40 // 下の句の4択を生成(正解+不正解3つ) 41 const wrongChoices = karutaList 42 .filter(k => k.number !== currentKaruta!.number) 43 .sort(() => Math.random() - 0.5) 44 .slice(0, 3) 45 .map(k => k.lower); 46 47 const allChoices = [...wrongChoices, currentKaruta.lower].sort(() => Math.random() - 0.5); 48 49 allChoices.forEach(choice => { 50 const button = document.createElement('button'); 51 button.textContent = choice; 52 button.onclick = () => checkAnswer(choice); 53 choicesDiv.appendChild(button); 54 }); 55 56 // お気に入りボタンの状態を更新(`includes()` を使わない方法) 57 let isFavorite = false; 58 for (let i = 0; i < favoriteList.length; i++) { 59 if (favoriteList[i] === currentKaruta.number) { 60 isFavorite = true; 61 break; 62 } 63 } 64 favoriteButton.textContent = isFavorite ? '★' : '☆'; 65 66 nextButton.style.display = 'none'; 67} 68 69function checkAnswer(selected: string) { 70 const result = document.getElementById('result')!; 71 const nextButton = document.getElementById('nextButton')!; 72 const scoreDisplay = document.getElementById('scoreDisplay')!; 73 74 if (!currentKaruta) return; 75 76 totalCount++; 77 78 if (selected === currentKaruta.lower) { 79 correctCount++; 80 result.innerHTML = `正解!🎉`; 81 result.style.color = 'green'; 82 } else { 83 result.innerHTML = `残念!正解は「${currentKaruta.lower}`; 84 result.style.color = 'red'; 85 } 86 87 // 正答率を更新 88 const accuracy = totalCount > 0 ? ((correctCount / totalCount) * 100).toFixed(1) : '0'; 89 scoreDisplay.textContent = `成績: ${correctCount} / ${totalCount} (正答率: ${accuracy}%)`; 90 91 nextButton.style.display = 'inline-block'; 92} 93 94// お気に入りを保存 95function saveFavorites() { 96 localStorage.setItem('favorites', JSON.stringify(favoriteList)); 97} 98 99// お気に入りを読み込む(型を保証) 100function loadFavorites(): number[] { 101 const data = JSON.parse(localStorage.getItem('favorites') || '[]'); 102 return Array.isArray(data) ? data.map(num => Number(num)) : []; 103} 104 105// お気に入り登録・削除(`includes()` を使わない方法) 106function toggleFavorite() { 107 const favoriteButton = document.getElementById('favoriteButton')!; 108 if (!currentKaruta) return; 109 110 let index = -1; 111 for (let i = 0; i < favoriteList.length; i++) { 112 if (favoriteList[i] === currentKaruta.number) { 113 index = i; 114 break; 115 } 116 } 117 118 if (index !== -1) { 119 // すでに登録されている場合は削除 120 favoriteList.splice(index, 1); 121 favoriteButton.textContent = '☆'; 122 } else { 123 // 新規追加 124 favoriteList.push(currentKaruta.number); 125 favoriteButton.textContent = '★'; 126 } 127 saveFavorites(); 128} 129 130// 「次の問題」ボタン 131document.getElementById('nextButton')!.addEventListener('click', nextQuestion); 132document.getElementById('favoriteButton')!.addEventListener('click', toggleFavorite);

投稿2025/03/08 03:28

jimunomado

総合スコア20

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.31%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問