TypeScript - pass to constructor entire object

typescript constructor
typescript multiple constructors
typescript initialize class object
typescript clone = object
typescript array of objects
typescript extend class
typescript extract properties from object
typescript interface constructor

I have a class at type script:

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

I want to force class instances to have only properties that class declaration has.

For example, if I get from firebase an object:

myFirebaseService.getChild(id).then(function(child){
  var currentChild = new Child(child);
}) 

So when the object is: {name:"ben", color:"db"}, I want the result to be:

currentChild = {"name":"ben"}

Becouse "color" is not field of "child".

I tried this:

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

  constructor(tempChild:Child = null) {
    if (tempChild){
      for (var prop in tempChild) {
        this[prop] = tempChild[prop];
      }
    }
  }
}

But it is not help. "currentChild" get all of the fields and attached them to the class instance.

(Of course, I can use the following code:

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

  constructor(tempChild:Child = null) {
    if (tempChild){
      this.nam  = tempChild.name;
      this.age =tempChild.ageÏ;
    }
  }
}

, but my truth class has many fields, and I want short code)

[New Feature] Initialize Classes by Using an Object Initializer � Issue , Which allows you to initialize an object inline, without specifying the object everytime. You could do something like this, which ensures you pass all required you end up having to have really verbose constructors full of optional params and @rihei bear in mind that classes in TypeScript do not play by any means the� Yes it is totally fine to pass the entire object as a property. The syntax is the same, so just create a property for the entire object. @Component({ selector: 'my-component' }) export class MyComponent{ @Input() item; } <my-component [item]=item></my-component>

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.

constructor, The constructor method is a special method for creating and initializing an object created within a class. If your class is a derived class, the default constructor calls the parent constructor, passing along any arguments that were provided: constructor(args) JavaScript � Tutorials: Complete beginners. Function seemed odd, since it's obviously an object instead of a function. But that's because of how JavaScript works; classes are just special functions: class Foo { constructor() { // the constructor } bar() { // a method } } Becomes

In my opinion the cleanest way to build your class instances from an arbitrary object would be using destructuring. You still have assignments for all your fields, but you have (very clean) control over what happens if the field doesn't exists, and also what fields you will assign to your classes fields:

export class Child {
  name:string
  age:number

  constructor({name = 'default name', age = 0} = {}) {
    this.name = name
    this.age = age
  }
}

Now this lets you create your instances from Objects or anys or any partial object literals, but when using literals it won't let you add extra stuff, which seems like is what you need:

const c0 = new Child({} as any /* as Object works as well */)
const c1 = new Child({}) // Literal, will be using defaults
const c2 = new Child() // No argument, using defaults only
const c3 = new Child({ name: 'a', age: 1 })
const c4 = new Child({ name: 'b', foo: 'bar'}) // error with foo

Generated js will check for everything that you would check manually:

define(["require", "exports"], function (require, exports) {
    "use strict";
    var Child = (function () {
        function Child(_a) {
            var _b = _a === void 0 ? {} : _a, _c = _b.name, name = _c === void 0 ? 'default name' : _c, _d = _b.age, age = _d === void 0 ? 0 : _d;
            this.name = name;
            this.age = age;
        }
        return Child;
    }());
    exports.Child = Child;
});

Try and see in the playground what is generated from this!

Interfaces � TypeScript, If the object we pass to the function meets the requirements listed, then it's allowed. On the last line of the snippet you can see that even assigning the entire In this example, we define two interfaces, ClockConstructor for the constructor� If they want their object constructor, they should use it, but just imagine how it would be cool if compiller would help you to build the object like in C#. Even groovy support this feature. It is easier way to initialize object with intellisense supporting where when you type the word you get some hint, if property exist, of course .(like in C#).

Constructor, operator "new", All JavaScript values are objects except primitives. Object constructor: In JavaScript, there is a special constructor function known as Object() is used to full-stack-img last_page JavaScript | Passing parameters to a callback function. The above code gets the entire constructor code as a string and applies a regex to get all 'words'. The first word should be 'function' and the second word should be the name of the class. Hope this helps.

JavaScript, But when we pass an object to a method, the situation changes dramatically, because Defining a constructor that takes an object of its class as a parameter. The problem with the code above is that we must pass an object that implements the whole UserModel interface, otherwise typescript will be 😡. But in our case, we want to be dynamic and not be committed to the entire interface, but still get IntelliSense.

Passing and Returning Objects in Java, In the above example, we pass values to the object to initialize the member variables. When we instantiate a new object, the class constructor is called with the� In TypeScript, we support much the same types as you would expect in JavaScript, with a convenient enumeration type thrown in to help things along. Boolean # The most basic datatype is the simple true/false value, which JavaScript and TypeScript call a boolean value.

Comments
  • I think new keyof feature of typescript 2.1 might be handy for you.
  • @AlekseyL. No, because his problem is a runtime one.
  • Similar (not identical) question that may be of help - stackoverflow.com/questions/22875636/…
  • Check this: stackoverflow.com/a/58788876/2746447 no need to duplicate fields 3 times