checking

Type in Typescript

Krantibrid
2 min readOct 19, 2020

TypeScript is an open-source language that builds on JavaScript. Types provide a way to describe the shape of an object, provide better documentation, and allows TypeScript to validate that our code is working correctly. By understanding JavaScript, TypeScript saves our time catching errors and providing fixes before we run the code.

Types

Types are simply labels that a particular value has or we can say that every value has a type. Its an easy way to refer to the different properties and functions that a value has. Lets try to understand what that means.

types and their values

Types of types !!🤔

A type is categorized into 2 main types

1. Primitive types
2. Object types.

Primitive types

It contains all the basics types.
example: number, string, boolean, void, null, undefined, symbol.

Object types

It contains all the types that we create for writing our code.
example: functions, classes, arrays, objects, etc.

Why do we care about types?

The two main reasons why we care about types are:

1. Types are used by typescript compiler to analyze or code for any errors. It checks whether the value is the same as its type. Consider the following example

interface Activity {
id: number,
activity: string
isCompleted: boolean
}
axios.get(url).then(response => {
const myActivity = response.data as Activity
})

The above interface Activity ensures that the response we get adheres to the types specified by the Activity. response.data as Activity is checking for the type here.

2. Types ensure that the other engineers too are aware of what values are flowing around the code. Types provide annotation for the values. In the above example, just by looking at the interface Activity, the programmer would get to know what to expect from the response.data i.e id should be expected to be always a number, activity a string, and isCompleted a boolean.

Where to use them?

Everywhere! Types are used everywhere in typescript code and that is the whole purpose of writing any code in typescript. Every value we define is going to have a type associated with it and typescript will use these types to check for any error present in the code.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response