svelte-check & TypeScript
ในโปรเจกต์ React คุณรัน tsc --noEmit เพื่อจับ type error ในไฟล์ .tsx ทั้งหมด ทำงานได้เพราะ TypeScript เข้าใจ JSX โดยกำเนิด แต่ template ของ Svelte ไม่ใช่ JSX — เป็น syntax เฉพาะตัวที่ tsc ไม่สามารถ parse ได้ จึงเป็นที่มาของ svelte-check: เครื่องมือ CLI ที่เข้าใจโครงสร้างไฟล์ .svelte รัน TypeScript compiler บนบล็อก <script lang="ts"> และยังตรวจสอบ type ของ expression ใน template เช่น การอ้างอิงตัวแปร reactive และการ destructure $props ด้วย
เปรียบเทียบ component แบบ TypeScript
หัวข้อที่มีชื่อว่า “เปรียบเทียบ component แบบ TypeScript”// Counter.tsximport React from 'react';
interface Props { initialCount: number;}
export function Counter({ initialCount }: Props) { const [count, setCount] = React.useState(initialCount); return ( <button onClick={() => setCount(c => c + 1)}> Count: {count} </button> );}<!-- Counter.svelte --><script lang="ts"> interface Props { initialCount: number; } let { initialCount }: Props = $props(); let count = $state(initialCount);</script>
<button onclick={() => count++}>Count: {count}</button>attribute lang="ts" บน <script> เป็นการเลือกให้บล็อกนั้นใช้ TypeScript คุณกำหนด interface Props ไว้ภายในบล็อก script โดยตรง (หรือ import มาจากไฟล์ที่ใช้ร่วมกัน) แล้ว destructure $props() ด้วย type นั้น
การรันตัวตรวจสอบ type
หัวข้อที่มีชื่อว่า “การรันตัวตรวจสอบ type”React/tsc:
npx tsc --noEmitSvelte:
npx svelte-check --tsconfig ./tsconfig.jsonทั้งสองคำสั่งจะแสดง error และ exit ด้วย code ที่ไม่ใช่ศูนย์หากมีปัญหาเรื่อง type ทำให้ใช้แทนกันได้ตรง ๆ ใน CI scripts
การเชื่อมต่อกับ IDE
หัวข้อที่มีชื่อว่า “การเชื่อมต่อกับ IDE”svelte-check เป็นพลังเบื้องหลังของส่วนขยาย Svelte for VS Code (และ language server อย่างเป็นทางการ) นี่คือเหตุผลที่คุณเห็น type error แบบ inline ใน template .svelte ในเอดิเตอร์ของคุณ — เอนจินตัวเดียวกันรันทั้งใน terminal และใน IDE
ติดตั้งส่วนขยายของ VS Code:
# Search in VS Code extensions panel:# "Svelte for VS Code" by the Svelte teamเพิ่ม svelte-check ลงในโปรเจกต์ของคุณ:
npm install --save-dev svelte-check typescripttsconfig.json ทั่วไปสำหรับโปรเจกต์ SvelteKit (สร้างโดย npm create svelte@latest):
{ "extends": "./.svelte-kit/tsconfig.json", "compilerOptions": { "allowJs": true, "checkJs": true, "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "resolveJsonModule": true, "skipLibCheck": true, "sourceMap": true, "strict": true }}