DEV Community

Cover image for What are Types in TypeScript
harshit mishra
harshit mishra

Posted on

What are Types in TypeScript

The Definition ๐Ÿฅธ

In TypeScript, Types are an easy way of to refer different properties and functions that a value has.

Let's break this sentence.

what is a value ๐Ÿค” :

Now, a value in TypeScript is anything that we can assign to a variable well we can assign numbers, strings, boolean, arrays, objects, and functions. all of these assignable entities have a type.

for example, let's take "Red" we might say it is a string or alternatively we can say that this is a value that will have all the properties and methods we assume a string can have.

Now a string has many functions and properties such as charAt(), concat(), and many more. length is one of the common property

console.log('Red'.length); // 3
console.log('Red'.chatAt(0)); // 'R'

two ways to look at a value

Conclusion ๐Ÿคจ

Now if we have to summerise "Red" by using all the properties and methods associated with it, that will be very inefficient.
A shorter way to refer to a value is to assign it a type. In this example, you say the 'Red' is a string. Then, you know that you can use the properties and methods of a string for the value 'Red'

thus Every value that we create has a type assigned to it, in some cases, it is very obvious such as the string in the example.

in Conclusion,
a type is a label that describes the different properties
and methods that a value has

Categories of types

Now in the world of TypeScript types are mainly characterised in 2 categories.

. primitive type
. Object type - Type that we build or are already built-in
TypeScript

categories of types

Need of Types โœจ

There are two main purposes of types in TypeScript:

  1. Types are used by the TypeScript compiler to analyze your code for errors

  2. Types allow us to understand what values are associated with variables and what values are flowing around in our codebase

Need of Types

Example of Types in TypeScript ๐Ÿ˜Ž

const color = 'red';

The TypeScript compiler knows that the type of color is string

example of type string

And it shows a list of methods of the string type that color can access:

list of methods on string

If you try to access a property or method that doesnโ€™t exist, the TypeScript compiler will show an error. For example:

error for unknown property name

Summary

  • Every value in TypeScript has a type.

  • A type is a label that describes the properties and methods that a value has.

  • TypeScript compiler uses types to analyze your code for hunting bugs and errors.

Top comments (0)