Make Mobile Apps with Ionic Framework 3 - Tutorial Part 6 #Type Assertion in TypeScript

in #programming9 years ago (edited)

typescript-2.0-awesomeness-image.jpg
Hey, SteemIt community. In this post I’m gonna show you the concept of the type assertions in Typescript. So I’m gonna start by declaring a variable and setting into a string.

let steem = “crypto”;

And here we can type steem. and look we get this beautifully intellisense on Visual Studio Code and this tooltip we can see all the things we can do with a string.

1.png

Soi on this items with this purple icons are functions. For example we have a function called endsWith. We can call this and see if this message end with s. And this returns a boolean.

let steem = “crypto”;
steem.endsWith(“s”);

So we can store the result in another variable. Like endsWithS.

let steem = “crypto”;
let endsWithS = steem.endsWith(“s”);

However, sometimes Typescript might be a little bit confuse about type of a variable. For example I’m gonna remove the initilization for steem variable. And initialize this variable on second line. Now look at type of steem variable.

let steem;
steem  = “crypto”;
let endsWithS = steem.endsWith(“s”);

2.png

It’s any because by default we don’t set a value the type is any. The problem in here, we delete the third line and write again, we don’t get intellisense anymore. Because endsWith someting that we can use with a string. Not type of any. So what we do?

In this case we need to explicitly tell Typescript compiler the steem variable actually a string. And this is what we call Type Assertions. How do we do Type Assertions?

There are two ways. One way is the prefix this variable with angle brackets and here it put the type like string. Now we need to close this part in parenthesis. Then if you pressed dot, you get a intellisense.

let steem;
steem  = “crypto”;
let endsWithS = (<string>steem).endsWith(“s”);

There is also another way do type assertion. Set another variable named steemIt. And type “as data type”.

let steem;
steem  = “crypto”;
let endsWithS = (<string>steem).endsWith(“s”);
let steemIt = (steem as string).endsWith(“s”);

The first approach is what you see more in a lot of tutorials out there. I just wanna clarify something here this type assertion does not change the type of this variable. It’s just tells Typescript compiler about the type of a variable. So we can access the intellisense.

Thanks for reading.

Previous Chapter: Types and Type Annotation in TypeScript

Next Chapter: Arrow Functions & Interfaces in TypeScript

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.082
BTC 59147.39
ETH 1559.63
USDT 1.00
SBD 0.42