Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript initialize object with partial object literal

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

like image 320
tru7 Avatar asked Feb 05 '18 12:02

tru7


People also ask

How do you initialize an object in TypeScript?

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", };

How do you initialize an empty object in TypeScript?

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.

How do you define object of objects type in TypeScript?

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.

How do you assign values to objects in TypeScript?

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.


1 Answers

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.

like image 161
Titian Cernicova-Dragomir Avatar answered Oct 12 '22 12:10

Titian Cernicova-Dragomir