TypeScript is a superset of JavaScript that offers optional static typing, type inference, and modern features to help catch errors at compile time and improve code readability.
What is a Type?
A type is a label that describes what kind of value something is — like a contract that says, “this variable should only hold this kind of data.”
Primitive data types:
However, you can also create your own types.
Type Assigment
In TypeScipt, we can assign types to different things.
In the following example, we set the type of "string" for a regular variable.
In the example above, we are telling TypeScript that the variable `isLoggedin` should always be a boolean. This will help us catch errors early on in the development process.
Types can be added to:
Type Inference
Type inference means that TypeScript automatically figures out the type of a variable or expression based on how you use it — you don’t always have to write the type yourself.
This is one of the big reasons to use TypeScript — even if you’re not writing explicit types everywhere, you still get safety and helpful feedback just by using the .ts file extension.
So overall, types in TypeScript help us catch errors early on and make our code more predictable and maintainable.
Custom Types
We can also define our own types in TypeScript with an object.
This is useful when we have an object that has a specific shape.
For instance, if we have an object that looks like this:
This is an example of a custom type called `User`.
It has three properties: `name`, `email`, and `age`. The `age` property is optional, meaning it doesn't have to be present in the object.
Then we can create an object of type `User` like this:
Types in Functions
We can also use types in functions. For instance, we can define a function that takes a `User` object as an argument:
We can also define the return type of a function. For instance, if we have a function that adds two numbers:
If you are destructuring, you can do the following:
Arrays
If you have an array and it should be all strings, you can do the following:
any Type
In TypeScript, there’s a special type called `any`, which disables type checking.
While it might seem flexible, it defeats the purpose of using TypeScript in the first place.
This works, but TypeScript won’t catch any type-related errors:
Generics
A generic is like a placeholder for a type.
Use it instead of any if you’re not sure what you’re getting back.
It lets you write a function or component that works with any type, while still keeping type safety.
We can improve the example above with a generic: