Shared Types का Package
In this page:
// index.ts of the shared package
export interface TypeName {
propertyName: type;
}
Core Concept
एक shared-types package एक छोटा, dependency-free TypeScript package है जिसमें दो या ज़्यादा दूसरे packages द्वारा उपयोग किए जाने वाले interfaces और types होते हैं — सबसे आम तौर पर एक frontend और एक backend जिन्हें API request/response shapes पर agree करना है।
उदाहरण: Core Concept
// packages/shared-types/index.ts
export interface CreateUserRequest {
email: string;
password: string;
}
console.log("A dependency-free package holding types shared across consumers");
Basic Setup
एक basic setup सिर्फ एक package.json है जिसमें compiled output की ओर point करता main/types field हो, एक tsconfig.json जो declaration files emit करने के लिए set हो, और एक index.ts जो हर shared type को re-export करे।
उदाहरण: Basic Setup
// package.json: { "main": "dist/index.js", "types": "dist/index.d.ts" }
// tsconfig.json: { "compilerOptions": { "declaration": true } }
console.log("index.ts re-exports every shared type from one entry point");
Typed Example
एक typed example shared package से interface CreateUserRequest { email: string; password: string } export कर सकता है, फिर वही exact interface एक Express route handler और एक React form component दोनों में import कर सकता है।
उदाहरण: Typed Example
export interface CreateUserRequest {
email: string;
password: string;
}
// Imported identically in both an Express handler and a React form
const req: CreateUserRequest = { email: "[email protected]", password: "secret" };
console.log(req);
Project Usage
एक असली project में, इस package को एक private npm registry पर publish करना (या एक monorepo में workspace protocol के ज़रिए इसे reference करना) का मतलब है कि एक shared type में backend API change तुरंत इसे consume करने वाले frontend में एक compile error के रूप में दिखता है।
उदाहरण: Project Usage
// A backend type change surfaces as a frontend compile error immediately
// once both packages import from the same shared-types package.
console.log("Publishing/workspace-linking keeps both sides in sync");
Best Practices
Shared-types package को runtime logic और framework-specific imports (कोई React नहीं, कोई Express नहीं) से मुक्त रखें ताकि यह lightweight रहे और literally किसी भी consumer से usable हो, उन non-JavaScript tooling सहित जो इसकी .d.ts files पढ़ते हैं।
उदाहरण: Best Practices
// Keep shared-types free of React/Express imports and runtime logic.
export interface ApiError {
message: string;
code: number;
}
console.log("Framework-free types stay usable from any consumer");
- Shared package में runtime code डालना, इसे heavy बनाना और hidden dependencies बनाना।
declaration: trueभूल जाना, इसलिए consumers को compiled package से कोई types नहीं मिलतीं।typesको एक.tsfile की ओर point करना जो built नहीं है, इसलिए publish होने के बाद imports fail होते हैं।
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: