In this blog post I want to provide a quick overview to some of the key concepts of TypeScript. First up, it’s important to note that TypeScript brings more features to ES6, but we have to transpile it to ES5 so that it can run on most browsers.
The most important feature provided by TypeScript is the addition of “type information”, which helps the developer create more secure and fail-safe code. In this way, it offers the possibility of adding types to variables in other languages, such as Java for example, and thus to control the parameters and other aspects of the code.
So, how do you use it? You only need to add “:” followed by the type you want. For example:
If we enter something that is not a number, for example: howMuch (‘a number’), it will fail in the compilation before Js occurs. Unlike what we currently do when creating variables along the way, TypeScript is more demanding and we have to declare the properties of the instance.
This is a TypeScript artifact that is not part of ECMAScript, it is an abstract type that has no code inside, and it defines the shape of an API. During transpilation, an interface will not generate any code, but TypeScript will use it to verify the type during development.
It also helps to define a variable with more than one type, for example:
Example if the interface describes a literal object:
They function as TypeScript interfaces, and they actually are like TypeScript, which compares custom types as “classes” and “interfaces”.
Taking the last example:
This is valid since they have the same “Shape.” If two objects have the same attributes, with the same characters, those two objects are considered the same type.
It is not necessary to always describe a type; TypeScript can infer the type of an object.
In this case, TypeScript infers that aCollectionOfNumbers is an array of numbers so when we try to assign an array of strings an error is generated.
We can use ‘type’ to define an alias to a type, for example:
This feature helps us define more than one possible type without the use of interfaces, for example:
And to improve things, use the keyword “type”:
These are combinations of two or more types, which are really useful for objects and parameters that must be implemented in more than one interface.
They are more specific than the “Function” type that we normally use, for example:
I hope this has been a helpful introduction to TypeScript. I’d love to hear your thoughts about it, so please leave a comment below!
July 08 / 2020
April 23 / 2020
As we gradually get used to our new COVID-19 reality, daily life from just a few weeks ago now feels like a lifetime away. For businesses this has created,...Read post