×
☰ See All Chapters

TypeScript Class Decorators

Class decorator accepts single parameter of type Function. Using Function parameter we can modify class definition. The function passed to this parameter is the constructor of the decorated class. Return value of the decorator is a replacement function to serve as the new constructor. Typescript will inject the constructor of the decorated class whenever a decorated class is detected.

Class decorator syntax :

function classDecoratorName(paramName : Function) {

}

TypeScript Class Decorators Example

classDecoratorDemo.ts

function classDecoratorDemo(param: Function) {

        console.log(`param : ${param}`);

        console.log(`decorated class constructor name : ${(<any>param).name}`);

        param.prototype.testProperty = "testProperty_value";

}

 

@classDecoratorDemo

class DecoratedClass {

}

 

let decoratedClassInstance = new DecoratedClass();

console.log(`decoratedClassInstance.testProperty : ${(<any>decoratedClassInstance).testProperty}`);

tsconfig.json

{

        "include": [

                "WebContent/ts/*"

        ],

        "compilerOptions": {

                "noEmitOnError": true,

                "outDir": "WebContent/js",

                "noImplicitAny": true,

                "experimentalDecorators": true

        }

}

welcome.html

<!DOCTYPE html>

<html>

    <body>

        <script src="../js/classDecoratorDemo.js"></script>

    </body>

</html>

 

File Structure

typescript-class-decorators-0

Output

typescript-class-decorators-1
 

All Chapters
Author