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'
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
Need of Types โจ
There are two main purposes of types in TypeScript:
Types are used by the TypeScript compiler to analyze your code for errors
Types allow us to understand what values are associated with variables and what values are flowing around in our codebase
Example of Types in TypeScript ๐
const color = 'red';
The TypeScript compiler knows that the type of color
is string
And it shows a list of methods of the string
type that color
can access:
If you try to access a property or method that doesnโt exist, the TypeScript compiler will show an error. For example:
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)