TypeScript is a statically typed language. A language is statically typed if the type of a variable is known at compile time. For some languages this means that you as the programmer must specify what type each variable is (e.g.: Java, C, C++); other languages offer some form of type inference, the capability of the type system to deduce the type of a variable.
Declaring types prevent many runtime errors and allow IDEs to do their magic and show you where the errors lie. If you’re coming from a typed language background like Java, you’d be used to seeing examples like this:
In TypeScript, the type of a variable is defined on the right-side before variable declaration. If we wanted to define the type of a variable name, it’ll look like the snippet below:
Types can be used:
- When declaring a variable
- In function parameters
- To type check the return value of a function
When declaring a variable in TypeScript, we make use of the let and const keywords. You can type check Arrays, Strings, Numbers etc.
Also, we can use the generic Array type Array, where elementType is the type of the element contained in the Array. An example looks like this:
Now if your Array will contain several types, the tuple comes into play.
Tuples Tuples allow you to declare an array where the type of a fixed number of elements is known, but need not be the same. For example, you may want to represent a value as a pair of a string and a number:
The last example is an Array with more than two characters, this didn’t error out because we supplied additional elements that were either a string or a number. If a boolean were to be added to the array, an error would be thrown.
Boolean A boolean is the most basic datatype. It is either true or false.
String Strings in TypeScript can be used in one of three ways:
- Double quotes.
- Single Quotes.
- Template literals.
Template literals: These are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called “template strings” in prior editions of the ES2015 specification. These strings are surrounded by the backtick/backquote (
Top comments (0)