TypeScript - pass to constructor entire object

前端 未结 3 1553
我在风中等你
我在风中等你 2020-12-11 18:48

I have a class at type script:

export class Child {
  name:string;
  age:number;
}

I want to force class instances to have only properties

3条回答
  •  隐瞒了意图╮
    2020-12-11 19:10

    You don't have many choices here, because the member definitions you make in the class before the constructor aren't being translated into javascript, the compiler leaves them out:

    class Child {
        name: string;
        age: number;
    
        constructor() {
            this.name = "name";
        }
    }
    

    Compiles into:

    var Child = (function () {
        function Child() {
            this.name = "name";
        }
        return Child;
    }());
    

    As you can see, the name member is the only one there, and even it is only used when assigned to.

    Because you need the names of the members in runtime, you'll need to have them set aside, for example in an array:

    class Child {
        private static MEMBERS = ["name", "age"];
    
        name: string;
        age: number;
    
        constructor(tempChild: Child = null) {
            if (tempChild) {
                for (var prop in tempChild) {
                    if (Child.MEMBERS.indexOf(props) >= 0) {
                        this[prop] = tempChild[prop];
                    }
                }
            }
        }
    }
    

    This isn't very comfortable to work with, so you can use decorators.
    For example:

    function member(cls: any, name: string) {
        if (!cls.constructor.MEMBERS) {
            cls.constructor.MEMBERS = [];
        }
    
        cls.constructor.MEMBERS.push(name);
    }
    
    function isMember(cls: any, name: string): boolean {
        return cls.MEMBERS[name] != null;
    }
    
    class Child {
        @member
        name: string;
    
        @member
        age: number;
    
        constructor(tempChild: Child = null) {
            if (tempChild) {
                for (var prop in tempChild) {
                    if (isMember(Child, prop)) {
                        this[prop] = tempChild[prop];
                    }
                }
            }
        }
    }
    

    (code in playground)

    It's not tested, so I'm not sure it's working, but if you decide to go that way then it's most of what you need.

提交回复
热议问题