I want to initialize an instance of a class with an object literal not containing all the elements in the class but whose elements are in the class.
class ATest{
aStr:string;
aNum:number;
result(){return this.aStr + this.aNum;}
}
let test=new ATest;
test={aStr:"hello",aNum:12}; // error, result() is missing in the object literal
What is the way to do that assignment exploiting the most of the validations of ts?
test=Object.assign(test,{aStr:"hello",aNom:12});
would work but then you miss the validation of the input fields - see aNom that's wrong but gets in
To initialize an object in TypeScript, we can create an object that matches the properties and types specified in the interface. export interface Category { name: string; description: string; } const category: Category = { name: "My Category", description: "My Description", };
Initialize Typed variable to an Empty Object in TypeScript # Use type assertions to initialize a typed variable to an empty object, e.g. const a1 = {} as Animal; . You can then set the properties on the object using dot or bracket notation. All of the properties you set on the object need to conform to the type.
In TypeScript, object is the type of all non-primitive values (primitive values are undefined , null , booleans, numbers, bigints, strings). With this type, we can't access any properties of a value.
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.
You have an object literal, an instance of a class must be created using new ClassName()
The simplest solution is to add a constructor accepting a Partial<T>
class ATest{
aStr:string;
aNum:number;
constructor(obj: Partial<ATest>) {
Object.assign(this, obj);
}
result(){return this.aStr + this.aNum;}
}
let test=new ATest({aStr:"hello",aNum:12});
Inside this new constructor you can do validations of the fields as required.
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