iT邦幫忙

2024 iThome 鐵人賽

DAY 12
0
自我挑戰組

React 開發者的 TypeScript 探索之旅系列 第 12

【 Day 12 】TypeScript - Strict Mode

  • 分享至 

  • xImage
  •  

本系列文章 GitHub

相信開發者們對 Todo List 肯定都不陌生,因此這次的範例選擇使用 Todo List 來當作我們練習 TypeScript 的主題。

首先,在 src 資料夾中新增一個 components 資料夾,並在該資料夾內新增一個 Todo.tsx,接著在 App.tsx 中引入這個元件。讓我們先用一些假資料來建立 Todo 這個元件:

export default function Todo() {
  return (
    <div className='flex items-center gap-[20px]'>
      <input type='checkbox' checked={false} />
      <p>Content</p>
      <button>Edit</button>
      <button>Delete</button>
    </div>
  )
}

執行 npm run dev,並打開瀏覽器前往 http://localhost:5173/,你應該會看到以下的畫面:

https://ithelp.ithome.com.tw/upload/images/20240922/20169025Zx1wvMkunG.png

到目前為止,這與我們平常在 React 開發中的流程是一樣的。但如果我們之後需要用 props 傳遞資料,會發生什麼呢?

export default function Todo(props) {
  return (
    <div className='flex items-center gap-[20px]'>
      <input type='checkbox' checked={false} />
      <p>Content</p>
      <button>Edit</button>
      <button>Delete</button>
    </div>
  )
}

當我們加入 props 後,會發現 props 出現紅色底線。將鼠標移到 props 上查看 IDE 提示的報錯內容:
https://ithelp.ithome.com.tw/upload/images/20240922/20169025Giav9d2KGj.png

錯誤訊息顯示:Parameter 'props' implicitly has an 'any' type.
這是因為我們在配置檔中啟用了 TypeScript 的嚴格模式 (strict 設定為 true)。然而,我們有兩個 tsconfig 配置檔,該查看哪一個呢?

還記得我們在 Day11 講過的嗎?tsconfig.app.json 主要負責前端的開發配置,而 tsconfig.node.json 是針對 Node.js 環境的配置。因此,我們需要查看 tsconfig.app.json 檔案。將 strict 設定改為 false,回到 Todo.tsx 文件,這時訊息變成了 Parameter 'props' implicitly has an 'any' type, but a better type may be inferred from usage.

這兩個錯誤訊息有什麼差別呢?

當嚴格模式開啟 (strict: true) 時,TypeScript 不允許變數或參數隱式地擁有 any 型別。這表示我們必須為 props 明確指定型別,否則 TypeScript 會報錯。嚴格模式的目的是防止隱式的 any 型別,以確保代碼的型別安全。

而當嚴格模式關閉 (strict: false) 時,TypeScript 允許隱式的 any 型別,這意味著即使沒有明確指定型別,TypeScript 也不會報錯。但它仍會發出警告,提示「雖然沒有指定型別,但可以從使用中推斷出更好的型別」。這是 TypeScript 的提示,建議你為 props 明確指定更合適的型別。

在後續的篇章中,我們會為 props 明確指定型別,因此可以將 strict 設定改回 true


上一篇
【 Day 11 】配置檔介紹
下一篇
【 Day 13 】為 React props 定義型別
系列文
React 開發者的 TypeScript 探索之旅17
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言