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...
Within the types, Typescript offers some very interesting options such as:
Literal types: You can specify to the variables that they will be a specific string or number.
Tuples: It is an array of fixed size to which you tell its type for each element.
Dynamic types: The any type allows that a variable stores a value of any type. To know the difference between any and unknow we can read this article.
Generic type: They are complex but very useful. It allows us to reuse code and, to summarize, it allows us to work with various types. You can read more about generics here.
Enum
They are a very interesting feature of this language. They assume a list of related values, which are constants.
Features
Functions are also typed, both what they return and each of their parameters.
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.
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.
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.
Type Assertion
Similar to type conversion, or casting, in other languages.
Naming
Typescript uses camelCase for variables, functions, attributes, properties and methods and PascalCase for Interfaces and Classes.
Top comments (0)