ข้ามไปยังเนื้อหา

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 ด้วย

React
// Counter.tsx
import 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>
);
}
Svelte
<!-- 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 นั้น

React/tsc:

Terminal window
npx tsc --noEmit

Svelte:

Terminal window
npx svelte-check --tsconfig ./tsconfig.json

ทั้งสองคำสั่งจะแสดง error และ exit ด้วย code ที่ไม่ใช่ศูนย์หากมีปัญหาเรื่อง type ทำให้ใช้แทนกันได้ตรง ๆ ใน CI scripts

svelte-check เป็นพลังเบื้องหลังของส่วนขยาย Svelte for VS Code (และ language server อย่างเป็นทางการ) นี่คือเหตุผลที่คุณเห็น type error แบบ inline ใน template .svelte ในเอดิเตอร์ของคุณ — เอนจินตัวเดียวกันรันทั้งใน terminal และใน IDE

ติดตั้งส่วนขยายของ VS Code:

Terminal window
# Search in VS Code extensions panel:
# "Svelte for VS Code" by the Svelte team

เพิ่ม svelte-check ลงในโปรเจกต์ของคุณ:

Terminal window
npm install --save-dev svelte-check typescript

tsconfig.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
}
}
ทำไมคุณถึงใช้ tsc เพียงอย่างเดียวตรวจสอบ type ของไฟล์ .svelte ไม่ได้?
คุณเปิดใช้งาน TypeScript ภายในบล็อก script ของ Svelte component อย่างไร?
npm script ใดที่รัน svelte-check ในโปรเจกต์ SvelteKit ทั่วไป?