Typescript for Angular developers

Mía Salazar - Jan 8 - - Dev Community

Versión en español

It's been two years since I started working with Angular and, I'm not going to lie, at first, Typescript seemed strange to me. I had never touched either technology before, so the .ts files were a bit difficult for me, given how different this framework developed by Google seemed to me. For this reason, here I am going to leave a series of tips for those who are new to Typescript.

What is it?
Typescript is a Javascript superset, that is, it can execute both Javascript and your own code. However, most browsers do not understand this language, so it needs to be transpiled to Javascript for it to be understood.

It was developed in 2012 because Javascript presented some problems when creating large-scale applications: it is not typed, it did not have classes or modules... For this reason, it was created by Microsoft, creating a language that, today, remains at the forefront.

Typed variables
Its main characteristic is that it is typed. We can specify the type of the variable after its name. This typing includes primitive types, such as booleans, arrays, objects...
Examples of typed code

Within the types, Typescript offers some very interesting options such as:

Enum
They are a very interesting feature of this language. They assume a list of related values, which are constants.
Enum example

Features
Functions are also typed, both what they return and each of their parameters.
Function example

Interfaces and classes
The interfaces are quite similar to other languages. They are a structure that defines a syntax that must be followed. Interfaces are not compiled, but are used to check typing.
Interface example

Optional properties
Related to interfaces, sometimes we want to indicate that some properties will be optional. To do this we use optional chaining, with a question mark.
Optional property example

Combined types
You can indicate that a variable will be of one type or another, and we can also tell it that it is a class that implements an interface.
Combined types example

Type Assertion
Similar to type conversion, or casting, in other languages.
Type Assertion example

Naming
Typescript uses camelCase for variables, functions, attributes, properties and methods and PascalCase for Interfaces and Classes.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .