Make Mobile Apps with Ionic Framework 3 - Tutorial Part 5 #Types and Type Annotation in TypeScript

in #programming9 years ago (edited)

0.jpg

Hi SteemIt community. In this post I’m gonna show you different data types we have in Typescript. Let me start by declaring a variable;

let steemItLevel = 41;

If I set different type with let keyword, this time we get an error. “[ts] Cannot redeclare block-scoped variable “steemItLevel”.

If I set different value have different type (like a word) without “let”” keyword to same variable, we immediately get a compilation error.

1.png

We can perfectly do this in Javascript because in Javacsript we can change the type of variables. But in Typescript wet get a compilation error.

Now, If I hover my mouse over this steemItLevel variable appear a tooltip. You can see a column and “number” after the variable. So this indicates type of steemItLevel variable in our program. So here Typescript compiler learn type of this variable should be number because a set it first number 41.

2.png

Now what if I declare a variable without initializing it? Let’s look at this type in hover.

let steemIt;

in mouser hover;

let a: any

It’s type is now “any”. Since right now we can exactly declare variable like in Javascript without errors.

let steemIt;
steemIt = 4;
steemIt = "steem";
steemIt = false;

Even Typescript doesn’t complain about this. So what’s the solution? If we don’t know value of variable ahead of time that’s when we use type annotation. So here we add column and after that just type of this variable like string. And look at second and fourth line, we got compilation errors.

3.png

Now in Typescript we have a few different types. So we have number which can include any integer or floating-point numbers. We have boolean which can be true or false. We have string which can be hold any character with quotes mark. We have any that you read earlier. We have arrays. Which can be array of numbers, array of strings or which can be array of any.

let s: number;
let t: boolean;
let e: string;
let seconde: any;
let m: number[];
let i: any[];

We also have another data type that is enum. So let say we’re working with the group of related constants like cryptocurrencies.

enum Cryptos {
    Steem,
    Bitcoin,
    Ethereum
}

Then we can declare a variable with these enum members;

let myFavoriteCrypto = Cryptos.Steem;

Now let’s compile this code and look what’s look like in Javascript;

var Cryptos;
(function (Cryptos) {
    Cryptos[Cryptos["Steem"] = 0] = "Steem";
    Cryptos[Cryptos["Bitcoin"] = 1] = "Bitcoin";
    Cryptos[Cryptos["Ethereum"] = 2] = "Ethereum";
})(Cryptos || (Cryptos = {}));
console.log(Cryptos.Steem);

Thanks for reading.

Previous Chapter: Variable Declaring in TypeScript

Next Chapter: Type Assertion in TypeScript

Coin Marketplace

STEEM 0.04
TRX 0.33
JST 0.082
BTC 61647.95
ETH 1649.19
USDT 1.00
SBD 0.42