TypeScript basic types with examples
You can try the below examples in the TypeScript playground.
We can decalare a variable to be type of
number the following way.
const aNumber: number = 10; /* will throw error for other types of values */ const aNumber: number = 'notANumber'; // Type '"notANumber"' is not assignable to type 'number'.
A variable to be type of
string the following way.
const aString: string = 'ten'; /* will throw error for other types of values */ const aNumber: string = 10; // Type '10' is not assignable to type 'string'.
Boolean values are either
const aBoolean: boolean = true;
We can declare an Array type in two ways. Also, it’s possible to declare array element types. We want to say that the variable is an array of certain types.
/* using type of elements followed by  */ const anArray: number = [1, 2, 3]; /* using generic array type */ let anArray: Array<number> = [1, 2, 3];
How do we declare an array of multiple elements type? For example, we can declare an array consisting of elements of both string and number types in the following way.
const anArrayOfMultipleTypes: (number | string) = [1, 'a', 2, 'b', 3, 'c']; // or const anArrayOfMultipleTypes: Array<number | string> = [1, 'a', 2, 'b', 3, 'c'];
number | string syntax is called union types. We’ll discuss about this in later posts.
any is particularly helpful while working with the 3rd party libraries whose types we might not know. It enables us to avoid compile-time type checking. Try to avoid it as much as possible because it removes the benefits of type checking.
let anUnknownType: any = 'a'; anUnknownType = 10; // TypeScript does not complain!
I’ve found that the above basic types are enough to get started with. There are more mechanisms to declare types that I’ll cover in future posts.