ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[Typescript] Extend Functionality of a TypeScript Class with Decorators

2021-01-14 04:32:23  阅读:12  来源: 互联网

标签:TypeScript console log Extend lessonNumber Typescript Lesson lesson class


In this lesson, you will learn how to extend a class's functionality through typescript decorators. Decorators provide a way to add both annotations and a meta-programming syntax for class declarations and members.

 

class Lesson {
    lessonNumber: number = 0;
}

const lesson = new Lesson();
console.log(lesson.lessonNumber); // 0

 

Decorator:

function classDecorator<T extends { new (...args: any[]): {}}>(target: T) {
    return class extends target {
        lessonNumber = 3;

        toString() {
            return `${target.name}::${JSON.stringify(this, null, 2)}`
        }
    }
}

@classDecorator
class Lesson {
    lessonNumber: number = 0;
}

const lesson = new Lesson();
console.log(lesson.lessonNumber); // 3
console.log(lesson.toString()) 
/**
 * "Lesson::{
        "lessonNumber": 3
    }"  
*/

 

标签:TypeScript,console,log,Extend,lessonNumber,Typescript,Lesson,lesson,class
来源: https://www.cnblogs.com/Answer1215/p/14275302.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有