An object literal is quick to build and does not need to have the data passed down a constructor or public
members to fill an object. An object literal is an efficient way to move data around. You can read a JSON file, receive the data from an Ajax call or from many sources, and cast to the desired type:
ajax.then((response:any)=>{ return response as DataTyped; };
However, if you have many functions or more complex logic that needs to be encapsulated, a class is more pragmatic. The reason is that using an object literal would require assigning the function on each instance manually. Also, a class can contain a private
function that you may not want to expose, provide encapsulation with private
/protected
and interfaces. An object literal's fields are public
and accessible. In the following example, we see data returned from an Ajax call. The expected type is ObjectDefinition
, which has a function. The function doesn't come for free...