TypeScript declaration file และ @types
.d.ts คืออะไร
declaration file (.d.ts) มี แต่ type ไม่มี code — บอก TS ว่า JavaScript module/global มี type อะไร
// math.d.ts
export function add(a: number, b: number): number;
export function subtract(a: number, b: number): number;
export const PI: number;// math.js — implementation จริง (JavaScript)
export function add(a, b) { return a + b; }
export function subtract(a, b) { return a - b; }
export const PI = 3.14159;TS ใช้ .d.ts ตอน type check, ใช้ .js ตอน runtime
@types — DefinitelyTyped
library JS จำนวนมากไม่มี type ในตัว — community เขียน .d.ts ไว้ที่ DefinitelyTyped publish เป็น @types/<ชื่อ>:
npm install express
npm install --save-dev @types/express # type ของ express
npm install lodash
npm install --save-dev @types/lodashTS หา @types/* ใน node_modules/@types/ อัตโนมัติ
library สมัยใหม่หลายตัว มี type ในตัว (zod, vitest, hono) — ไม่ต้องลง @types เช็คก่อน (ดู "types" field ใน package.json ของ library หรือลอง import แล้วดูว่ามี type ไหม)
library ที่ไม่มี type และไม่มี @types
TS จะ error: Could not find a declaration file for module 'some-lib'
ทางเลือก:
1. quick fix — declare module
// src/types/some-lib.d.ts
declare module "some-lib" {
export function doThing(input: string): number;
export interface Options {
verbose?: boolean;
}
const _default: (opts?: Options) => void;
export default _default;
}2. quickest (ไม่ปลอดภัย) — untyped
// src/types/some-lib.d.ts
declare module "some-lib"; // module นี้เป็น any ทั้งหมด3. ปิด error ชั่วคราว
// @ts-expect-error - some-lib ยังไม่มี type
import { doThing } from "some-lib";ให้ TS หาไฟล์ .d.ts ของเรา — ตรวจว่า include ครอบ src/types/:
{ "include": ["src/**/*"] }declare — ambient declaration
declare = “สิ่งนี้มีอยู่แล้ว (ที่อื่น) — บอก type ให้ TS”
global variable / function
// global.d.ts
declare const __APP_VERSION__: string; // จาก Vite define / webpack DefinePlugin
declare function gtag(command: string, ...args: unknown[]): void; // Google Analyticsเพิ่ม property ให้ global object
// global.d.ts
export {}; // ทำให้ไฟล์เป็น module (สำคัญ)
declare global {
interface Window {
dataLayer: unknown[];
myApp: {
version: string;
config: Config;
};
}
namespace NodeJS {
interface ProcessEnv {
DATABASE_URL: string;
PORT: string;
NODE_ENV: "development" | "production" | "test";
}
}
}window.myApp.version; // string (typed!)
process.env.DATABASE_URL; // string (แทน string | undefined)
process.envtyped แบบนี้ โกหกได้ (ไม่ validate) — zod ที่ boundary ดีกว่า (บทที่ 30) แต่ handy สำหรับ autocomplete
module augmentation — เพิ่ม property ให้ library type
// types/express.d.ts
import "express";
declare module "express-serve-static-core" {
interface Request {
user?: { id: string; role: string }; // เพิ่ม req.user
}
}app.use((req, res, next) => {
req.user = { id: "u1", role: "admin" }; // typed
next();
});(บทที่ 39 — Express)
non-JS imports (bundler)
// types/assets.d.ts
declare module "*.svg" {
const content: string;
export default content;
}
declare module "*.css";
declare module "*.json" {
const value: unknown;
export default value;
}Vite/webpack มี type พวกนี้ให้แล้วผ่าน vite/client / framework types — ตรวจก่อนเขียนเอง
สร้าง .d.ts จาก library ของเรา
// tsconfig.json ของ library
{ "compilerOptions": { "declaration": true, "declarationMap": true, "outDir": "dist" } }tsc จะสร้าง dist/*.d.ts คู่กับ dist/*.js — ผู้ใช้ library ได้ type ทันที (บทที่ 33)
เรื่องที่คนมักพลาด
- ลง
@types/xทั้งที่ x มี type ในตัว — ซ้ำ, ขัดกัน; เช็ค"types"field ก่อน declare globalในไฟล์ที่ไม่ใช่ module — ต้องมีexport {}(หรือ import/export อื่น) ให้ TS มองเป็น module.d.tsไม่อยู่ในinclude— TS ไม่เห็น; ตรวจinclude/typeRootsdeclare module "x";(ไม่มี body) — ทำให้ x เป็น any ทั้งหมด (เสีย type safety)@types/xเวอร์ชันไม่ตรงกับ x — API mismatch; อัปเดตคู่กัน- augment
process.envแล้วคิดว่า runtime ปลอดภัย — type เท่านั้น; validate ด้วย zod - แก้ไฟล์ใน
node_modules/@types/— หายเมื่อ reinstall; ใช้ module augmentation
สรุป
.d.ts— type-only, ไม่มี code; บอก TS ว่า JS มี type อะไร@types/<lib>(DefinitelyTyped) —npm i -D @types/expressสำหรับ lib ที่ไม่มี type ในตัว (lib สมัยใหม่มักมีในตัว)- lib ไม่มี type: เขียน
declare module "lib" { ... }เอง (หรือdeclare module "lib";= any) declare global { interface Window { ... } }(+export {}) — เพิ่ม property ให้ global- module augmentation —
declare module "lib" { interface X { ... } }— เพิ่ม property ให้ library type (เช่นRequest.user) - library ของเรา:
"declaration": true→tscสร้าง.d.tsให้
บทถัดไปว่าด้วยการสร้างและ publish library — build, dual ESM/CJS, exports/types field และ tsup