top of page

TypeScript for Beginners: What is Types?

TypeScript for Beginners: What is Types?

I. The Definition

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

II. Let's break this sentence

II.1. 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'
TypeScript for Beginners: What is Types?

III. Conclusion

Now if we have to summarize "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

III.1. Categories of types

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

  • Primitive type

  • Object type - Type that we build or are already built-inTypeScript

TypeScript for Beginners: What is Types?

III.2. 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.

TypeScript for Beginners: What is Types?

IV. Example of Types in TypeScript

const color = 'red';

The TypeScript compiler knows that the type of color is string

TypeScript for Beginners: What is Types?

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

TypeScript for Beginners: What is Types?

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

TypeScript for Beginners: What is Types?

V. 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.

Visit the part 2 of this series, Type Annotation vs Type Inference.

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
Stationary photo

Be the first to know

Subscribe to our newsletter to receive news and updates.

Thanks for submitting!

Follow us
bottom of page