Explicit Types in TypeScript


Data types can be explicitly declared in TypeScript. Although TypeScript automatically infers a data type on a variable declared.

Learning material used is Net Ninja's TypeScript course on YouTube.

Here is how it is done;

Example 1: Strings, Numbers and Booleans

let character: string; //character must remain a string and cannot be changed.
let age: number; //age must remain a number and cannot be changed.
let isLoggedIn: boolean; //isLoggedIn must remain a boolean and cannot be changed.

character = 'Peace';
age = 20;
isLoggedIn = true;

Example 2: Arrays

let ninjas: string[]; //this can only be an array of strings.

//To add items to the array using the push methood;
ninjas.push('hello'); //an error will occur.
//using the push method on the array will not work as it has not been initialized with a value.

//The array has to be initialized for the push method to work. It can be initialized as an empty array like this;
let ninjas: string[] = [];
ninjas.push('hello'); //this will now work

Example 3: Objects

let ninjaOne: object; //ninjaOne can only be an object and no other data type.
ninjaOne = { name: 'yoshi', age: 30 };

//ninjaOne can be declared as an array like this;
ninjaOne = []; //this is allowed because an array is a kind of object.

//to be more explicit when using objects, it can be done like this
let ninjaTwo: {
    name: string,
    age: number,
    beltColor: string

ninjaTwo = { name: 'mario', age: 30, beltColor: 'black' }