Node.js รัน TypeScript โดยตรงตั้งแต่ v23.6.0 - node app.ts ไม่ต้องคอมไพล์!
Node.js 23.6+ รองรับไฟล์ .ts/.mts/.cts แบบ native ด้วย type stripping ลบ type annotation รันทันที รองรับ ESM/CommonJS
Node.js TypeScript Support
| ไฟล์ | รองรับ | หมายเหตุ |
|---|---|---|
.ts | ✅ | Standard TypeScript |
.mts | ✅ | ES Module TS |
.cts | ✅ | CommonJS TS |
.tsx | ❌ | React JSX |
รัน TypeScript ทันที
# ง่ายสุด
node app.ts# ESM project
node --loader tsx app.ts
# Experimental features
node --experimental-transform-types app.ts
ตัวอย่างใช้งานจริง
app.ts
// Type annotations ลบอัตโนมัติ
interface User {
id: number;
name: string;
}async function getUser(id: number): Promise<User> {
return { id, name: `User ${id}` };
}
// รันได้เลย node app.ts
const user = await getUser(1);
console.log(user);
package.json
{
"type": "module",
"scripts": {
"dev": "node --watch app.ts",
"start": "node app.ts"
}
}
ESM Import ต้องระบุ .ts
// ✅ ถูกต้อง
import { handler } from './routes.ts';
import express from 'express';// ❌ Error - ไม่รู้ extension
import { handler } from './routes';
ข้อจำกัดสำคัญ
❌ ไม่มี type checking (ต้อง tsc --noEmit)
❌ tsconfig.json ถูก ignore
❌ Decorators/JSX ต้อง flag
❌ ไม่แปลง const enum/private fields
✅ Syntax TS 99% รองรับ
Production Setup แนะนำ
// tsconfig.json (type check เท่านั้น)
{
"tsBuildInfoFile": ".cache/tsbuildinfo",
"noEmit": true,
"strict": true
}
// package.json
{
"scripts": {
"typecheck": "tsc --noEmit",
"dev": "tsx watch src/index.ts",
"start": "node dist/index.js",
"build": "tsc"
}
}
Performance Comparison
| Method | Cold Start | Memory | Build Step |
|---|---|---|---|
| node app.ts | 25ms | 80MB | ❌ None |
| tsc → node | 35ms | 75MB | ✅ Type check |
| tsx | 45ms | 120MB | ⚠️ Runtime |
VS Code Config
// settings.json
{
"typescript.preferences.includePackageJsonAutoImports": "on",
"typescript.suggest.autoImports": true,
"node.experimentalTypeAcquisition": true
}
Migration Guide
1. Node.js >= 23.6.0 ✅
2. package.json "type": "module"
3. ระบุ .ts extension ทุก import
4. tsc --noEmit (type check)
5. node app.ts 🚀