TypeScript - pass to constructor entire object -
i have class @ type script:
export class child { name:string; age:number; }
i want force class instances have properties class declaration has.
for example, if firebase object:
myfirebaseservice.getchild(id).then(function(child){ var currentchild = new child(child); })
so when object is: {name:"ben", color:"db"}, want result be:
currentchild = {"name":"ben"}
becouse "color" not field of "child".
i tried this:
export class child { name:string; age:number; constructor(tempchild:child = null) { if (tempchild){ (var prop in tempchild) { this[prop] = tempchild[prop]; } } } }
but not help. "currentchild" of fields , attached them class instance.
(of course, can use following code:
export class child { name:string; age:number; constructor(tempchild:child = null) { if (tempchild){ this.nam = tempchild.name; this.age =tempchild.ageĆ; } } }
, truth class has many fields, , want short code)
you don't have many choices here, because member definitions make in class before constructor aren't being translated javascript, 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 can see, name
member 1 there, , used when assigned to.
because need names of members in runtime, you'll need have them set aside, example in array:
class child { private static members = ["name", "age"]; name: string; age: number; constructor(tempchild: child = null) { if (tempchild) { (var prop in tempchild) { if (child.members.indexof(props) >= 0) { this[prop] = tempchild[prop]; } } } } }
this isn't comfortable work with, can use decorators.
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) { (var prop in tempchild) { if (ismember(child, prop)) { this[prop] = tempchild[prop]; } } } } }
it's not tested, i'm not sure it's working, if decide go way it's of need.
Comments
Post a Comment