DEV Community

Cover image for Typescript: Types
Jatin Sharma
Jatin Sharma

Posted on

Typescript: Types

In this article, we are going to learn about how we will use typescript to make sure that variable type is secure and no other value can manipulate that variable. For example: string value cannot be assigned to a numeric variable.

This is going to be a full series of typescript where you will learn from basic topics like string, boolean to more complex like Type Aliases, enums, Interface, generics, and etc.

Table of Contents

Types in Typescript

  • number
  • string
  • boolean
  • null
  • undefined
  • void
  • object
  • array
  • tuples
  • unknown
  • never
  • any (should not use)

and many more.

Situations to use Typescript

For example, there is a function increaseScore and it takes currentScore and increases the score by increaseBy number and returns the updated score.

function increaseScore(currentScore, increaseBy){
    return currentScore + increaseBy;
}

increaseScore(10, 2) // output : 12
increaseScore(10, "2") // output : 102
Enter fullscreen mode Exit fullscreen mode

If someone passes the string or other thing, then it will throw an error in the production or runtime. Such as in the second example where the score becomes 102 it's a bug as shown in the image.

Now, How can we prevent that using typescript? We will look at the later in depth. You can define the type of a variable like this-

let variableName: type = value;
Enter fullscreen mode Exit fullscreen mode

Primitive Types

Primitive types in JavaScript are-

  • string
  • boolean
  • number

string

String values are surrounded by single quotation marks or double quotation marks. They are used to store text data.

let player: string = "John";

// ✅ CORRECT
player = "anny";

// ❌ ERROR: Type 'number' is not assignable to type 'string
player = 4;
Enter fullscreen mode Exit fullscreen mode

As you can see we assign the name (Anny) in line 3 and we assign the number in line 4 and it immediately throws an error. It's what typescript is. You don't need to run the TS to get the error as JS does.

boolean

In boolean it could be either true or false otherwise, it will throw you an error as shown in the following code-

let isLoggedIn: boolean = false;

// ✅ CORRECT
isLoggedIn = true;

// ❌ ERROR: Type 'number' is not assignable to type 'boolean'
isLoggedIn = 5;

// ❌ ERROR: Type 'string' is not assignable to type 'boolean'.
isLoggedIn = "hello";
Enter fullscreen mode Exit fullscreen mode

number

JavaScript does not have a special runtime value for integers, so there’s no equivalent to int or float - everything is simply number that's why in line 5 when we assign the price to 500.53 it doesn't give you an error because it's a number.

let price: number = 200;

// 👇✅ CORRECT
price = 300;
price = 500.53;

// 👇❌ Error
price = false;
price = "3000";
Enter fullscreen mode Exit fullscreen mode

Don't use `any`

So the question occurred that why Shouldn't we use any? The answer is simply because when you use any then you disable all the type checking for that variable and anyone can assign any kind of value to the variable. For example:

// 👇 Wrong Practice (by default 'any')
let hello;

// 👇 'hello' can take any type of value
hello =  2;
hello =  "world";
hello =  true;
Enter fullscreen mode Exit fullscreen mode

On line: 1 we have not defined the type of the variable hello so its defaults as any and you can assign whatever you want as shown in the above example.

Now Imagine the scenario where you are calling an API and getting the data in the string format, but someone changes it to the boolean or number then your whole app functionality will crash due to that mistake. And Typescript prevents you from doing that. For example:

let data; // type by default is any

function getData(){
    //.........API Call
    return  "Message";
}

data = getData();       // no issue because expected string
Enter fullscreen mode Exit fullscreen mode

Another Example:

let data;

function getData(){
    //.........API Call
    return 823;
}

data = getData();       // ISSUE: expected string but returns the number (won't throw error because type is `any`)
Enter fullscreen mode Exit fullscreen mode

Solution:

let data: string;

function getData(){
    //.........API Call
    return  "Message";
}

data = getData();
Enter fullscreen mode Exit fullscreen mode

Now, if you pass something that is not a string then it will throw an error as shown below:

let data: string;

function getData(){
  //........API Call
  return true;
}

// ❌ ERROR: Type 'boolean' is not assignable to type 'string'
data = getData();
Enter fullscreen mode Exit fullscreen mode

You can use any whenever you don’t want a particular value to cause type-checking errors.

I'll cover void, never and others later in this series.

Wrapping up

In this article, I explained how you can use typescript to make sure that variable type is secure and no other value can manipulate that variable.

This is a series of Typescript that will help you to learn Typescript from the scratch. If you enjoyed this article, then don't forget to give ❤️ and Bookmark 🏷️for later use and if you have any questions or feedback then don't hesitate to drop them in the comments below. I'll see in the next one.

Connect with me

Twitter GitHub LinkedIn Instagram Website Newsletter Support

Top comments (7)

Collapse
 
technoph1le profile image
Technophile

Hey, there! Great article. One question though... How did you create that series section (part 1, 2 and e.t.c)? I couldn't find anywhere how to do it.

Collapse
 
j471n profile image
Jatin Sharma • Edited

Thanks mate. :)

When you are about to publish you article there is a hexagonal icon next to Save Button. Click on it. A modal will show up and you can find the Series section at the end of that modal. You can create a new series or choose the existing one.

Image description

Collapse
 
technoph1le profile image
Technophile

Thanks :)

Thread Thread
 
j471n profile image
Jatin Sharma

My pleasure ✨

Collapse
 
hudsonpufferfish profile image
Hudson Nguyen

tysm :D Your explanation is really understandable for me tbh

Collapse
 
j471n profile image
Jatin Sharma

I am glad you enjoyed. :)

Collapse
 
rappayne profile image
Rap Payne

When you're CALLING an API, TypeScript cannot help you. It is only enforced at compile time and an API call happens at run time.
My biggest problem with TypeScript is that it makes devs think that they're protected when by the time your code is running, every TypeScript protection has been compiled away.
I'd recommend you rewrite your example, maybe? Don't call it getData() or just don't say that it's calling an API. HTH.