Vivasoft-logo

5.2 ক্লাস ডেকোরেটর্সঃ

একটি ক্লাস ডেকোরেটর ক্লাসের আগে ডিক্লেয়ার করা হয়। এটি ক্লাস কন্সট্রাক্টরে এপ্লাই করা হয় এবং এর সাহায্যে ক্লাসটিকে পর্যবেক্ষণ, সংশোধন ও প্রতিস্থাপন করা হয়।

ক্লাস ডেকোরেটর এক্সপ্রেশনটি (expression) ফাংশন হিসাবে রানটাইমে কল হয়, যেখানে ডেকোরেটর ক্লাসের কন্সট্রাক্টরটি একমাত্র আর্গুমেন্ট হিসেবে গণ্য করা হয়।

ক্লাস ডেকোরেটর যদি কোন মান রিটার্ন করে, সেটা কন্সট্রাক্টর ফাংশন দ্বারা ক্লাস ডিক্লারেশনকে প্রতিস্থাপন করবে।

যদি আমরা @sealed ক্লাস ডেকোরেটর হিসাবে bugReport ক্লাসে প্রয়োগ করিঃ

				
					@sealed
class bugReport {
  type: string = "Duct Tape ";
  title: string;
 
  constructor(t: string) {
    this.title = t;
  }
}
				
			

আর আমরা sealed ক্লাসকে এভাবে ডিক্লেয়ার করি:

				
					function sealed (constructor: Function) {
  Object.seal(constructor);
  Object.seal(constructor.prototype);
}
				
			

যখনই sealed ক্লাসটি এক্সিকিউট হবে, তখন কন্সট্রাক্টর এবং তার প্রোটোটাইপ বদ্ধ হয়ে যাবে এবং রানটাইমে এর উপর কোন পরিবর্তন হতে প্রতিরোধ করবে।

নিচের উদাহরণটিতে আমরা দেখতে পারি কিভাবে ক্লাসের কন্সট্রাক্টরকে ওভাররাইড করা যায়:

				
					function reportableClassDecorator<T extends { new (...args: any[]): {} }>(constructor: T) {
  return class extends constructor {
  reportingURL = "http://www...";
  };
}
 
@reportableClassDecorator
class BugReport {
  type: string = "report";
  title: string;
 
  constructor(t: string) {
    this.title = t;
  }
}
 
const bug = new BugReport("Needs dark mode");
console.log(bug.title); // Prints "Needs dark mode"
console.log(bug.type); // Prints "report"
 
// Note that the decorator _does not_ change the TypeScript type
// and so the new property `reportingURL` is not known
// to the type system:
console.log(bug.reportingURL);
Property 'reportingURL' does not exist on type 'BugReport'.
				
			

উপরের উদাহরণটিতে, reportableClassDecorator ডেকোরেটরটির সাহায্যে আমরা ক্লাসটির কন্সট্রাক্টরটি ওভাররাইডের চেষ্টা করি। কিন্তু ডেকোরেটর টাইপস্ক্রিপ্টের টাইপ বদলে দিতে পারে না, তাই আমরা দেখতে পাই, reportingURL নামক নতুন প্রোপার্টির টাইপ না জানা থাকায় সে unknown property হিসাবে গণ্য হয়।