#Returning an object

9 messages · Page 1 of 1 (latest)

knotty kite
#

Hello guys I would like to get your opinion on something, in Typescript is there a difference between :
return new ObjectType();
return {} as ObjectType;

Which one is more idiomatic or a better practice overall ? and are there any cons for each one ?

austere scaffold
#

There is a huge difference and which to use depends on what ObjectType is

#

the new ObjectType() syntax is how you construct an instance of an ES6 class

#

{} is an empty object literal, a direct construction of an empty object

#

in this case you are casting it to the type ObjectType, which is a strange thing to do with something you are returning and probably breaking type safety

#

As to which is more idiomatic between classes and plain objects, that entirely depends on what you want to do with it, which programming paradigm you prefer etc.

#

e.g. people who like OOP tend to gravitate towards classes, people who prefer imperative or functional style programming tend to use plain objects more often

knotty kite
#

That's very interesting, thank you so much @austere scaffold !

austere scaffold
#

yw