This code showcases the distinction between a plain object and a class in TypeScript:
const object = {
prop1: 'prop1',
prop2: 'prop2'
};
The object
is of type Object
.
In contrast, we define a class using TypeScript syntax:
class SpecificClass {
prop1: string;
prop2: string;
}
The prototype
of this class is SpecificClass
.
Although both have matching properties with the same types, you cannot directly use the plain object as an instance of the class due to their different prototype
. To convert the plain object to a class instance, you need to create a new instance of the class (in this case SpecificClass
) and assign the properties from the plain object. This step involves creating a new object and setting its prototype to be that of SpecificClass
.
const classInstance = new SpecificClass();
classInstance.prop1 = object.prop1;
classInstance.prop2 = object.prop2;
Now, classInstance
represents an instance of SpecificClass
with values equivalent to those of the plain object. The process essentially converts the plain object into a class instance. JSON to Class converters operate similarly underneath the surface.
The documentation also suggests:
Prefer using an interface over a class, especially when dealing with responses that are plain objects and cannot be directly converted into class instances.
In TypeScript, interfaces serve this purpose:
interface ISpecificObject {
prop1: string;
prop2: string;
}
Interfaces function differently in TypeScript compared to other statically typed languages—they employ Duck Typing to verify if an object conforms to an interface based on its structure (methods and properties). As long as the object aligns with the interface in terms of signature, it can be used seamlessly without conversion. Therefore, passing the object
variable where ISpecificObject
is expected is valid without any intermediate steps.