DEV Community

youxufkhan
youxufkhan

Posted on

Getting Started with TypeScript: Types

Type

What is Type?

Easy way to refer to different properties + functions that a value has.

Let's learn from an example

"red"

What do you see above, it's a string. That's right. But also
It is a value that has all the properties + methods that we assume that a string has

Properties + Methods a 'string' has in JS

charAt(), charCodeAt(), concat(), includes(), endsWith(), indexOf(), lastlndexOf(), localeCompare(), match(), length and so on....

I hope you understand from the above example what a type is.

Categories of Types

In the world of typescript there are two different categories of types.

  1. Primitive Types
  2. Object Types

Primitive Types

Primitive types are all the basic types you might guess.

  • number
  • string
  • boolean
  • symbol
  • void
  • null
  • undefined

Object Types

These are any types you create or any other types that are built into language itself.

  • functions
  • classes
  • arrays
  • Objects

Why do we care about types?

  1. Types are used by the Typescript Compiler to analyze our code for errors
  2. Types allow other engineers to understand what values are flowing around our codebase

Examples of Types

const today = new Date();
Enter fullscreen mode Exit fullscreen mode

I created a variable that is an instance of a Date object, if I hover of that variable my code editor will tell me the type of value this variable is pointing at.

const today: Date

Typescript can now use this information to decide what we can do with this variable. For example if we use this variable and put a dot at the end, I will see my autocomplete pop up here.

Typescript

This is listing out all the different functions and properties a Date object has. Typescript knows that because it has internal definition of what a Date is.

Similarly if we try to reference a value that a doesn't exist in the Date object, we will immediately see an error.

Typescript

Now lets create a plain JavaScript Object.

const person = {
    age: 20,
    getAge: function(): number {
        return this.age;
    }
}
Enter fullscreen mode Exit fullscreen mode

If I hover over the variable now, it will show all the properties and the method the object has.

Typescript

I hope by these examples you have the basic idea of types in TypeScript. We will discuss more about each of these in the later posts.

Top comments (0)