Here's a snippet in which I instantiate a new content
object in my service:
const newContent = new Content(
result.obj.name
result.obj.user.firstName,
result.obj._id,
result.obj.user._id,
);
The problem is that this way of object instantiation relies on the order of properties in my content
model. I was wondering if there's a way to do it by mapping every property to the value I want to set it to, for example:
const newContent = new Content(
name: result.obj.name,
user: result.obj.user.
content_id: result.obj._id,
user_id: result.obj.user._id,
);
To instantiate an object with the constructor we create a new instance, as we did before. However, this time we pass the values we want between the parentheses to assign them to the properties of the object. var object_name = new constructor_name(argument1, argument2);
To use the Object. assign() method in TypeScript, pass a target object as the first parameter to the method and one or more source objects, e.g. const result = Object. assign({}, obj1, obj2) . The method will copy the properties from the source objects to the target object.
To add a property to an object in TypeScript, set the property as optional on the interface you assign to the object using a question mark. You can then add the property at a later point in time without getting a type error. Copied!
Syntax. var object_name = { key1: “value1”, //scalar value key2: “value”, key3: function() { //functions }, key4:[“content1”, “content2”] //collection }; As shown above, an object can contain scalar values, functions and structures like arrays and tuples.
const newContent = <Content>({
name: result.obj.name,
user: result.obj.user.
content_id: result.obj._id,
user_id: result.obj.user._id,
});
Here you can instantiate an object and use type assertion or casting to the Content type. For more information on type assertion: https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions
You can pass an object to the constructor which wraps all of those variables:
type ContentData = {
name: string;
user: string;
content_id: string;
user_id: string;
}
class Content {
constructor(data: ContentData) {
...
}
}
And then:
const newContent = new Content({
name: result.obj.name,
user: result.obj.user.
content_id: result.obj._id,
user_id: result.obj.user._id,
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With