TypeScriptAdvanced
Modules ও Type Declaration
import type, declaration files (.d.ts), @types packages, declare module ও global typing — বাংলায়।
15টি অংশবাংলা ভাষায়
TypeScript-এ modules শুধু value নয় — টাইপও ভাগ হয়। একটি ফাইল export করলে সেখানকার টাইপ অন্য ফাইলে import করা যায়।
import type
// types.ts
export interface User {
id: number;
name: string;
}
// app.ts — টাইপ স্পষ্ট বলাই ভালো
const user: User = { id: 1, name: "রহিম" };Declaration File (.d.ts)
.d.ts ফাইলে শুধু টাইপ ঘোষণা থাকে — runtime code নেই। লাইব্রেরির ধরন describe করতে এবং JavaScript-এ লেখা কোডে টাইপ দিতে ব্যবহৃত হয়।
math.d.tstypescript
typescript
export function add(a: number, b: number): number;
export const VERSION: string;@types packages
JavaScript লাইব্রেরি ব্যবহারে টাইপ পেতে DefinitelyTyped-এর @types/... নামে install করতে হয়।
# Node.js global type
npm install -D @types/node
# Express-এর টাইপ
npm install -D @types/express
# React-এ ডিফল্ট ভাবে টাইপ সহ আছে (react + @types/react)declare module
টাইপ নেই এমন module বা global value ঘোষণা করার জন্য declare ব্যবহার হয়।
env.d.tstypescript
typescript
// কোনো module-এর ধরন নিজে ঘোষণা
declare module "*.png" {
const src: string;
export default src;
}
// global variable
declare const API_BASE_URL: string;Ambient ও Global
// Windows-এ custom বৈশিষ্ট্য যোগ
declare global {
interface Window {
__analyticsId?: string;
}
}
// export না থাকলে এটি module-এ পরিণত হয় নারুলস মনে রাখুন
value-ও ব্যবহার করলে import, শুধু টাইপ হলে import type (tree-shaking-এ সহায়ক)। লাইব্রেরিতে টাইপ পাওয়া যায় না মানে @types/... খুঁজুন।
শেষ প্যারায় নিজে practice করুন — কোড কপি করে নিজের এডিটরে চালিয়ে দেখুন।