DEV Community

Discussion on: How the TypeScript Required Type Works

peerreynders profile image
peerreynders • Edited on

but what's the "type" keyword? Is it like "class"?

No. A class is a template for creating objects.

A type alias is simply a name for a type. A type alias can describe an object type, union type, tuple type or array type.

Typescript is structurally typed. Languages like C# and Java are nominally typed which means that if two types have different names they are always treated as separate types. That is not the case with TypeScript.

If you have two types that go by a different names, TypeScript will treat them as equivalent if they have an identical shape. In the case of an object type the "shape" is derived from the key/value type pairs found on the object (regardless of order).

People more comfortable with class-oriented implementations tend to use interface and then extend them when implementing their classes. But plain objects can satisfy an interface, so there is no need to implement a class; a factory function for creating objects or even an object literal is good enough.

The one unique property of interfaces is that they merge so it's possible to declare an interface in bits and pieces and then objects have to implement all the merged requirements in order to satisfy the interface.

With type types can be intersected which basically combines the requirements of the intersected types (with a type union you only satisfy one of the types that comprise the union).

intersection versus union of types

My personal opinion is that type aliases are more versatile as they can represent more than just object types. However when you are implementing classes and/or need declaration merging then interface can make sense.

While classes are types not all types are classes.

fathidevs profile image

Thank you for the detailed explanation, appreciated so much